0

I'm getting two outputs when I log this code:

private void meth(Date date) {
    LOG.info(
        date.toInstant()
        .atZone(ZoneId.systemDefault())
        .format(DateTimeFormatter.ISO_DATE_TIME));

    LocalDateTime ldt = LocalDateTime.ofInstant(
        date.toInstant(),
        ZoneId.systemDefault()
    );

    LOG.info(ldt.format(DateTimeFormatter.ISO_DATE_TIME));

}

I'm getting these logs:

2019-04-01 13:13:32.195  INFO --- : 2019-01-01T01:00:00+01:00[Europe/Madrid]
2019-04-01 13:13:32.197  INFO --- : 2019-01-01T01:00:00

Has ldt lost its original time zone?

How could I care that?

Ruslan
  • 5,827
  • 1
  • 19
  • 36
Jordi
  • 18,082
  • 29
  • 125
  • 263

2 Answers2

4

You are using a LocalDateTime, which does not contain a timezone - see API:

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

You want to use a ZonedDateTime instead.

Michael
  • 37,794
  • 9
  • 70
  • 113
Mena
  • 46,817
  • 11
  • 84
  • 103
1

LocalDateTime is a date-time without a time-zone:

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html

Peter Šály
  • 2,668
  • 2
  • 11
  • 25