How to change the time based on timezone in LocalDateTime, here i have built a date with Time zone as EST, now i need to find the UTC of the corresponding time. please help me how to solve this
String str = "16Jun2015_153556";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMMyyyy_HHmmss");
formatter.withZone(ZoneId.of("EST5EDT"));
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
You shouldn't think about "changing the time zone" of a LocalDateTime
- a LocalDateTime
doesn't have a time zone. Instead, you should build a ZonedDateTime
from a LocalDateTime
and a time zone (ZoneId
). First remove the formatter.withZone
call, then use:
ZonedId zone = ZoneId.of("EST5EDT"); // Or preferrably "America/New_York"
ZonedDateTime zoned = ZonedDateTime.of(dateTime, zone);
Then you could convert that to an instant, or perhaps use:
ZonedDateTime utc = zoned.withZoneSameInstant(ZoneOffset.UTC);
So for example:
import java.time.*;
import java.time.format.*;
public class Test {
public static void main(String[] args) {
String str = "16Jun2015_153556";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMMyyyy_HHmmss");
ZoneId zone = ZoneId.of("America/New_York");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
ZonedDateTime zoned = ZonedDateTime.of(dateTime, zone);
// Both of these print 2015-06-16T19:35:56Z
System.out.println(zoned.toInstant());
System.out.println(zoned.withZoneSameInstant(ZoneOffset.UTC));
}
}
See more on this question at Stackoverflow