0

Arn't both System.currentTimeMillis() vs Timestamp.valueOf(LocalDateTime.now(UTC)).getTime() suppose to give same number, Try and find out that it doesn't.

What is the reason for this, Arn't both suppose to give same number ie no of milisec from 1970 ?

user204069
  • 1,215
  • 3
  • 19
  • 25
  • No. You should neither use `LocalDateTime` nor `Timestamp` for this. Not `LocalDateTime` because it doesn’t define a point in time, which you need for the millis. Not `Timestamp` because it’s poorly designed (a true hack on top of the already poorly designed `Date`) and long outdated. `Instant.now().toEpochMilli()` is another good option (see for example [Which one is recommended: Instant.now().toEpochMilli() or System.currentTimeMillis()](https://stackoverflow.com/questions/58705657/which-one-is-recommended-instant-now-toepochmilli-or-system-currenttimemill)). – Ole V.V. Feb 11 '20 at 05:30

1 Answers1

2

If you read the documentation, the javadoc of Timestamp.valueOf​(LocalDateTime dateTime) says:

The provided LocalDateTime is interpreted as the local date-time in the local time zone.

Since the LocalDateTime in the UTC time zone, not the local time zone, the result is a time zone shift to JVM's default time zone. If you remove ZoneOffset.UTC from the now() call, or use ZoneId.systemDefault() instead, it'll work as you expected.

Alternatively, if you do have a LocalDateTime in UTC, and want to convert to Timestamp, you need to say the LocalDateTime is in UTC:

LocalDateTime ldt = LocalDateTime.now(UTC); // cannot change time zone
long millis = Timestamp.from(ldt.atZone(UTC).toInstant()).getTime(); // so specify time zone

Of course, the values will still not necessarily be equal, since a few milliseconds of time may have passed between the two calls.

Andreas
  • 154,647
  • 11
  • 152
  • 247