将时间戳设置为 Java 中的当前时间

Setting timestamp to current time in Java

我正在尝试将 java EE7 网络应用程序中的当前日期时间设置为我拥有的 apache derby 数据库。

我在 java 和 derby 中都使用时间戳,所以我不必担心类型转换。

但是,我知道获取当前日期时间的唯一方法是通过 calendar.set(日历时间)。

是否有固有的方法来设置时间戳的当前日期时间,或者我需要使用转换器吗?

您可以使用日期 class 初始化为当前时间,即:

Timestamp timestamp = new Timestamp(new Date().getTime());

java.util.Calendarclass是对Date对象的抽象封装。 日历为日期字段提供 getter 和 setter,仅此而已。这是有代价的。

在您的情况下,使用简单的 Date 是理想的。

使用以下代码。

Timestamp timestamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

使用 joda jar 并导入所需的包。

DateTime d = new DateTime().withZone(DateTimeZone.forID(TIME_ZONE));