tl;dr
You truncated the fractional second.
Same as doing this…
Instant.now().truncatedTo( ChronoUnit.SECONDS ).toEpochMilli()
Details
You divided by one thousand, and then multiplied by one thousand on a count of milliseconds. You effectively truncated the fractional seconds from a date-time value defined as a count of milliseconds since the epoch reference of the first moment of 1970 in UTC (1970-01-01T00:00:00Z
).
You are using a troublesome old date-time class, java.util.Date
, now legacy, supplanted by the java.time classes.
The equivalent class in java.time is Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now(); // Current moment in UTC.
To truncate any fractional second, do so by calling methods rather than using your math approach. This makes your code more self-documenting. And date-time work is tricky, so avoid roll-your-own solutions.
Instant instantWholeSeconds = instant.truncatedTo( ChronoUnit.SECONDS );
I strongly advise against tracking date-time values as a count-from-epoch. It makes debugging difficult as humans cannot discern the date-time meaning from a very long integer. Furthermore, epochs vary with at least a couple dozen in use by various systems. And granularities of such counts vary, with various systems using whole seconds, milliseconds, microseconds, nanoseconds, and other amounts as well. So count-from-epoch numbers are commonly ambiguous and prone to misinterpretation.
But if you insist, you can extract a count-from-epoch from an Instant
. Remember that going to milliseconds as your count involves data loss as any nanoseconds will be truncated.
// WARNING: Data-loss. Truncating any nanoseconds.
// CAUTION: Tracking date-time as count-from-epoch is *not* advised.
long millis = instant.toEpochMilli();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.