Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add current timestamp to Date object in Java?

Tags:

java

date

I need to pass in a Date object into a service which my API is calling. I have the info on the day, month, and year for the Date but also need a timestamp. The service is expecting it in this format:

<date>2015-04-01T00:00:00-05:00</date>

How can I add something to the Date to get this format?

like image 605
Connie Avatar asked Jun 26 '26 11:06

Connie


1 Answers

Never use java.util.Date. Supplanted by java.time.Instant.

Get your date portion.

LocalDate ld = LocalDate.of( 2015 , 4 , 1 ) ;

Or use the readable Month enum.

LocalDate ld = LocalDate.of( 2015 , Month.APRIL , 1 ) ;

Get the time of day when the day starts in some particular time zone. Do not assume the day starts at 00:00:00, may be some other time such as 01:00:00. Let java.time figure that out for you.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;

Generate a string in your desired format, a standard ISO 8601 format.

DateTimeFormatter f = DateTimeFormatter.ISO_OFFSET_DATE_TIME ;
String output = zdt.format( f ) ;

To see that moment in UTC, extract a Instant.

Instant instant = zdt.toInstant() ;

Conversion

If you must inter-operate with old code not yet updated for java.time, you can call new conversion methods added to the old classes. These include Date::from( Instant ).

java.util.Date d = java.util.Date.from( instant ) ;

Going the other direction.

Instant instant = d.toInstant() ;

Get back to a time zone other than UTC.

ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;  // Same moment, different wall-clock time. 
like image 194
Basil Bourque Avatar answered Jun 28 '26 23:06

Basil Bourque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!