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
  • 6,090
  • 1
  • 21
  • 36
Jordi
  • 20,868
  • 39
  • 149
  • 333

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
  • 41,989
  • 11
  • 82
  • 128
Mena
  • 47,782
  • 11
  • 87
  • 106
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,848
  • 2
  • 12
  • 26