简体   繁体   中英

Setting timestamp to current time in Java

I'm trying to set the current datetime in a java EE7 web app to an apache derby database I have.

I'm using timestamp in both java and derby so I don't have to worry about type conversions.

However, the only way I know of to get the current datetime is through calendar.set(Calendar time).

Is there inherent way to set the current datetime for timestamp or will I need to use a converter?

You can use the Date class for initializing to the current time , ie :

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

The java.util.Calendar class is an abstract encapsulation of the Date object. Calendar provides getter and setter for the date fields , nothing more. And it comes at a cost.

In your case using a simple Date is ideal.

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

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

使用以下代码。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM