SelfTaught
SelfTaught

Reputation: 283

Java 8 - Convert LocalDate to ZonedDateTime

I'm new to java.time package. I have a LocalDate 2015-12-10. I need to convert this to ZonedDateTime. Time should be 00:00:00 and Zone is ZoneOffset.UTC.

After conversion, ZonedDateTime should be 2015-12-10T00:00:00+02:00.

I'm storing the LocalDate in a variable called startDate.

I tried:

ZonedDateTime.ofInstant(Instant.from(startDate), ZoneOffset.UTC)

but get the error

java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: 2015-12-10 of type java.time.LocalDate]

I also tried:

startDate.atStartOfDay().atZone(ZoneOffset.UTC)

This gives unexpected results.

I looked at the API and tried a few other methods, but no luck so far.

Is there any other way to convert LocalDate to ZonedDateTime?

Upvotes: 25

Views: 38623

Answers (4)

Shafeeq Mohammed
Shafeeq Mohammed

Reputation: 1298

public ZonedDateTime transformToZonedDateTime(String Date, String timeZone) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    LocalDate localDate = LocalDate.parse(Date, formatter);
    LocalDateTime localDateTime = localDate.atTime(LocalTime.now());
    ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneOffset.UTC);
    ZoneId zoneId = ZoneId.of(timeZone);
    return zonedDateTime.withZoneSameInstant(zoneId);
}

INPUT: deliveryDate = "18-05-2023" and timeZone = "Asia/Hong_Kong"

RETURNS: "2023-05-19T20:43Z"

Upvotes: 0

cheparsky
cheparsky

Reputation: 530

If you need to convert LocalDate to ZonedDateTime with current time you can use this one:

LocalDate localDate = LocalDate.parse("2017-07-22"); 
LocalDateTime localDateTime = localDate.atTime(LocalTime.now());
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault())

Upvotes: 1

Luc S.
Luc S.

Reputation: 1234

I supose the issue isn't relevant anymore but for google-purposes:

  LocalDate localDate = LocalDate.parse("2017-07-22");      
  ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
  // => 2017-07-22T00:00+05:30[Asia/Kolkata]

source https://beginnersbook.com/2017/10/java-convert-localdate-to-zoneddatetime/

Upvotes: 2

JodaStephen
JodaStephen

Reputation: 63385

When converting less specific objects to more specific ones, use the 'at' methods:

ZonedDateTime zdt = startDate.atStartOfDay(ZoneOffset.UTC);

Passing in the UTC offset will not get a result of +02:00 however, which suggests you are trying to achieve something else.

Upvotes: 53

Related Questions