I have a UTC date-time like this (a String): 2022-11-22T17:15:00
And a ZoneID like this: "America/Tijuana"
Using java.time API, I want to get the actual datetime for that zone, which is: 2022-11-22T09:15:00 (the time is 09:15 instead of 17:15)
- ZonedDateTime.toLocalDateTime() returns:
2022-11-22T17:15 - ZonedDateTime.toString() returns:
2022-11-22T17:15-08:00[America/Tijuana]
None of the above gives me what I'm looking for.
This is my code:
ZoneId zonaID = ZoneId.of('America/Tijuana');
CharSequence dateUTC = "2022-11-22T17:15:00";
LocalDateTime dateTimeL = LocalDateTime.parse(dateUTC);
ZonedDateTime myZDT = ZonedDateTime.now();
ZonedDateTime myZDTFinal = myZDT.of(dateTimeL, zonaID);
System.out.println("using toLocalDateTime: " + myZDTFinal.toLocalDateTime());
System.out.println("using toString: " + myZDTFinal.toString());
I know that this might be a duplicated question but there's so many questions about date-times and I just haven't been able to figure out this.
Any help will be really appreciated.
There can be many ways to achieve the result. A simple approach would be
LocalDateTime.OffsetDateTimeat UTC usingLocalDateTime#atOffset.OffsetDateTime#atZoneSameInstantto convert the resultingOffsetDateTimeinto aZonedDateTimeatZoneId.of("America/Tijuana").LocalDateTimeout of the resultingZonedDateTimeby usingZonedDateTime#toLocalDateTime.LocalDateTimeinto the desired string.Demo:
Output:
Note that
LocalDateTime#toStringremoves second and fraction-of-second values if they are zero. Suppose you want to keep them (as you have posted in your question), you can use aDateTimeFormatteras shown above.An alternate approach:
Alternatively, you can append
Zat the end of your ISO 8601 formatted date-time string to enableInstantto parse it and then convert theInstantinto aZonedDateTimecorresponding to theZoneId.of("America/Tijuana")by usingInstant#atZone. The symbol,Zrefers to UTC in a date-time string.The rest of the steps will remain the same.
Demo:
Output:
Learn more about the modern Date-Time API from Trail: Date Time.