Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert LocalDateTime to LocalDateTime in UTC

Convert LocalDateTime to LocalDateTime in UTC.

LocalDateTime convertToUtc(LocalDateTime date) {      //do conversion  } 

I searched over net. But did not get a solution

like image 981
Sarika.S Avatar asked Jan 06 '16 05:01

Sarika.S


People also ask

Is LocalDateTime a UTC?

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.

How do I convert LocalDateTime to another timezone?

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.

How do I parse LocalDateTime to ZonedDateTime?

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.

How do I get LocalDateTime timezone?

// 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.


2 Answers

I personally prefer

LocalDateTime.now(ZoneOffset.UTC); 

as it is the most readable option.

like image 159
slorinc Avatar answered Oct 03 '22 21:10

slorinc


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()); 
like image 25
Fatih Arslan Avatar answered Oct 03 '22 22:10

Fatih Arslan