Reputation: 41
We are using Java8 in our project.I have startDate in String format "2021-12-31" which I am receiving from from an 3RD party.
I have to pass it to our consumer via our model.Model accepts java.util.Date and the format should be yyyy-MM-dd.
I wrote the below code:
String strDate="2021-12-31";
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
java.util.Date parsedDate=(Date)df.parse(strDate);
Expected output : parsedDate = 2021-12-31
Actual Output: parsedDate= Tue Dec 07 00:00:00 GMT +5.30 2021.
Please help.
Upvotes: 0
Views: 3181
Reputation: 339669
No, Tue Dec 07 00:00:00 GMT +5.30 2021
could not be the result of your code. Even accounting for time zone issues, the result could not be different by weeks. Please take more care when posting here, to not waste people's time.
The actual results of your code will be something more like the following. See for yourself.
Fri Dec 31 00:00:00 GMT 2021
Or, setting the JVM’s current default time zone to Asia/Kolkata
:
Fri Dec 31 00:00:00 IST 2021
Notice that those two results are different moments, several hours apart. The day starts earlier in India than at UTC/GMT prime meridian. So the results of this code vary by the current default time zone — not good!
You are using terrible date-time classes that were years ago supplanted by the modern java.time classed defined in JSR 310.
Your input string complies with the ISO 8601 standard used by default in the java.time classes when parsing/generating text. So no need to specify a formatting pattern.
For a date-only value, without time of day, and without time zone or offset-from-UTC, use LocalDate
.
LocalDate ld = LocalDate.parse( "2021-12-31" ) ;
You said:
Model accepts java.util.Date and the format should be yyyy-MM-dd
Well, (a) that is unfortunate, (b) a Date
object does not have a "format", it has a date-time value rather than text, and (c) a java.util.Date
represents a moment, a specific point on the timeline rather than a date-only. A Date
object represents a date with time-of-day as seen in UTC (an offset from UTC of zero hours-minutes-seconds).
The best solution is to fix your design to use proper types.
If you cannot fix the faulty design and must employ a hack, then perhaps you could use the first moment of the day on that date as seen in UTC.
ZonedDateTime zdt = ld.atStartOfDay( ZoneOffset.UTC ) ;
Instant instant = zdt.toInstant() ;
Convert from modern class to legacy class by calling new conversion methods added to the old classes.
java.util.Date d = Date.from( instant ) ;
Dump to console.
System.out.println( "ld.toString(): " + ld ) ;
System.out.println( "zdt.toString(): " + zdt ) ;
System.out.println( "instant.toString(): " + instant ) ;
System.out.println( "d.toString(): " + d ) ;
See this code run live at IdeOne.com.
ld.toString(): 2021-12-31
zdt.toString(): 2021-12-31T00:00Z
instant.toString(): 2021-12-31T00:00:00Z
d.toString(): Fri Dec 31 00:00:00 GMT 2021
Upvotes: 3