You ask for the fraction of a second of the current time as a number of milliseconds (not count from epoch).
Instant.now() // Get current moment in UTC, then…
.get( ChronoField.MILLI_OF_SECOND ) // interrogate a `TemporalField`.
2017-04-25T03:01:14.113Z ?
113
See this code run live at IdeOne.com.
The modern way is with the java.time classes.
Capture the current moment in UTC.
Instant.now()
Use the Instant.get
method to interrogate for the value of a TemporalField
. In our case, the TemporalField
we want is ChronoField.MILLI_OF_SECOND
.
int millis = Instant.now().get( ChronoField.MILLI_OF_SECOND ) ; // Get current moment in UTC, then interrogate a `TemporalField`.
Or do the math yourself.
More likely you are asking this for a specific time zone. The fraction of a second is likely to be the same as with Instant
but there are so many anomalies with time zones, I hesitate to make that assumption.
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) ;
Interrogate for the fractional second. The Question asked for milliseconds, but java.time classes use a finer resolution of nanoseconds. That means the number of nanoseconds will range from from 0 to 999,999,999.
long nanosFractionOfSecond = zdt.getNano();
If you truly want milliseconds, truncate the finer data by dividing by one million. For example, a half second is 500,000,000 nanoseconds and also is 500 milliseconds.
long millis = ( nanosFractionOfSecond / 1_000_000L ) ; // Truncate nanoseconds to milliseconds, by a factor of one million.
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
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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?
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.