Home > Software design >  Converting string to date 2021-12-10T00:00:00 in java
Converting string to date 2021-12-10T00:00:00 in java

Time:12-04

I'm tring to convert this date string "2021-12-10T00:00:00" into a Date but when i deserialize it i got this.

Thu Dec 09 19:00:00 COT 2021. it seems I'm losing one day.

Can anyone help me?

"startDate": "2021-12-10T00:00:00", and the result is this 2021-12-09T19:00:00.000-0500

CodePudding user response:

tl;dr

java.util.Date.from(
    LocalDateTime
    .parse( "2021-12-10T00:00:00" ) 
    .atZone( 
        ZoneId.of( "America/Bogota" )
    )
    .toInstant()
)

Details

I am guessing that you are using the terrible legacy date-time classes such as Date and Calendar. Don’t. Use only java.time class.

Your input string complies with the ISO 8601 standard for date-time formats. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

LocalDateTime ldt = LocalDateTime.parse( "2021-12-10T00:00:00" ) ;

You said:

I'm tring to convert this date string "2021-12-10T00:00:00" into a Date

That does not make sense.

I assume by “Date”, you meant a java.until.Date. That legacy class represents a moment, a point on the timeline as seen in UTC, that is, with an offset from UTC of zero hours-minutes-seconds.

But your input lacks an indicator of time zone or offset. For example, if that string was meant to represent a moment as seen in UTC, it should have had a Z appended.

I am guessing that you assume the input was meant to represent a moment as seen in Colombia.

ZoneId z = ZoneId.of( "America/Bogota" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

Now we have determined a moment as seen through the wall-clock time used by the people of Colombia.

Generally best to avoid java.util.Date class. But if you must, to interoperate with legacy code not yet updated to java.time, you can convert.

java.util.Date d = Date.from( zdt.toInstant() ) ;

CodePudding user response:

Your start date is 2021-12-10 00:00:00 GMT 0 and your result is 2021-12-09 19:00:00 GMT-5. These times are the same. You can pass a Locale to your SimpleDataFormat constructor to be able to configure the used time zone.

  • Related