Reputation: 68
I am trying to send a date via JSON using a format like "date":"2018-01-03"
but in my Java code I get 2018-01-03 02:00:00
and not 2018-01-03 00:00:00
as I would expect. Seems like it is adding some timezone to my date. Is this alright or am I missing something?
Upvotes: 1
Views: 583
Reputation: 338306
To represent a date-only value, use a date-only type rather than a date+time-of-day type.
LocalDate
LocalDate
represents a date without a time-of-day and without a time zone.
LocalDate ld = LocalDate.of( "2018-01-03" ) ;
ZonedDateTime
To get the first moment of the day, specify a time zone.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
Instant
To view that same moment in UTC, extract an Instant
object from the ZonedDateTime
.
Instant instant = zdt.toInstant() ;
These topics have been discussed many many times already. Search Stack Overflow for more info.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Upvotes: 1
Reputation: 2217
From the Java API "The class Date represents a specific instant in time, with millisecond precision." When you create a Date you automatically get a date with a time. If you want to send just the date you have some options: 1. Convert the date to a string on the server side using the desired format. 2. On the client side ignore the time. 3. On the server side, zero the time fields, using methods such as setMinutes(0). But please note that these methods are deprecated in favor of Calendar methods, and further the old Date and Calendar classes are replaced by the Java 8 date and time classes.
Upvotes: 0