Convert LocalDateTime to LocalDateTime in UTC.
LocalDateTime convertToUtc(LocalDateTime date) { //do conversion }
I searched over net. But did not get a solution
The LocalDateTime class represents the date-time,often viewed as year-month-day-hour-minute-second and has got no representation of time-zone or offset from UTC/Greenwich.
To convert a LocalDateTime to another time zone, you first apply the original time zone using atZone() , which returns a ZonedDateTime , then convert to the new time zone using withZoneSameInstant() , and finally convert the result back to a LocalDateTime . If you skip the last step, you'd keep the zone.
Convert LocalDateTime to ZonedDateTime The LocalDateTime has no time zone; to convert the LocalDateTime to ZonedDateTime , we can use . atZone(ZoneId. systemDefault()) to create a ZonedDateTime containing the system default time zone and convert it to another time zone using a predefined zone id or offset.
// your local date/time with no timezone information LocalDateTime localNow = LocalDateTime. now(); // setting UTC as the timezone ZonedDateTime zonedUTC = localNow. atZone(ZoneId. of("UTC")); // converting to IST ZonedDateTime zonedIST = zonedUTC.
I personally prefer
LocalDateTime.now(ZoneOffset.UTC);
as it is the most readable option.
LocalDateTime does not contain Zone information. ZonedDatetime does.
If you want to convert LocalDateTime to UTC, you need to wrap by ZonedDateTime fist.
You can convert like the below.
LocalDateTime ldt = LocalDateTime.now(); System.out.println(ldt.toLocalTime()); ZonedDateTime ldtZoned = ldt.atZone(ZoneId.systemDefault()); ZonedDateTime utcZoned = ldtZoned.withZoneSameInstant(ZoneId.of("UTC")); System.out.println(utcZoned.toLocalTime());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With