How to Get Milliseconds from Localdatetime in Java 8

How to get milliseconds from LocalDateTime in Java 8

I'm not entirely sure what you mean by "current milliseconds" but I'll assume it's the number of milliseconds since the "epoch," namely midnight, January 1, 1970 UTC.

If you want to find the number of milliseconds since the epoch right now, then use System.currentTimeMillis() as Anubian Noob has pointed out. If so, there's no reason to use any of the new java.time APIs to do this.

However, maybe you already have a LocalDateTime or similar object from somewhere and you want to convert it to milliseconds since the epoch. It's not possible to do that directly, since the LocalDateTime family of objects has no notion of what time zone they're in. Thus time zone information needs to be supplied to find the time relative to the epoch, which is in UTC.

Suppose you have a LocalDateTime like this:

LocalDateTime ldt = LocalDateTime.of(2014, 5, 29, 18, 41, 16);

You need to apply the time zone information, giving a ZonedDateTime. I'm in the same time zone as Los Angeles, so I'd do something like this:

ZonedDateTime zdt = ldt.atZone(ZoneId.of("America/Los_Angeles"));

Of course, this makes assumptions about the time zone. And there are edge cases that can occur, for example, if the local time happens to name a time near the Daylight Saving Time (Summer Time) transition. Let's set these aside, but you should be aware that these cases exist.

Anyway, if you can get a valid ZonedDateTime, you can convert this to the number of milliseconds since the epoch, like so:

long millis = zdt.toInstant().toEpochMilli();

LocalDateTime to milliseconds difference in Java 8 and Java 11

If you take a look at the difference:

Expected :<2021-06-02T14:06:21.820299>
Actual :<2021-06-02T14:06:21.820>

You can see that it removes anything less than a millisecond.

This happens because you convert the LocalDateTime to milliseconds:

.toInstant().toEpochMilli();

In order to avoid that, you can use Instant#getNano:

Gets the number of nanoseconds, later along the time-line, from the start of the second.
The nanosecond-of-second value measures the total number of nanoseconds from the second returned by getEpochSecond().

It could look like this:

Instant instant=expected.atZone(ZoneId.systemDefault())
.toInstant();
long epochMillis = instant.toEpochMilli();
long nanos=instant.getNano()%1000000;//get nanos of Millisecond

LocalDateTime actual = LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMillis).plusNanos(nanos),
TimeZone.getDefault().toZoneId());

Why did it work in Java 8?

As this post and JDK-8068730 Increase the precision of the implementation of java.time.Clock.systemUTC() describes, Java 8 did not capture time units smaller than a millisecond. Since Java 9, LocalDateTime.now (and similar) get the time with microseconds.

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

If you have the milliseconds since the Epoch and want to convert them to a local date using the current local timezone, you can use Instant.ofEpochMilli(long epochMilli)

LocalDate date =
Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate();

but keep in mind that even the system’s default time zone may change, thus the same long value may produce different result in subsequent runs, even on the same machine.

Further, keep in mind that LocalDate, unlike java.util.Date, really represents a date, not a date and time.

Otherwise, you may use a LocalDateTime:

LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());

How to create a long time in Milliseconds from String in Java 8 with LocalDateTime?

You can create DateTimeFormatter with input formatted date and then convert into Instant with zone to extract epoch timestamp

String date = "2019-12-13_09:23:23.333";
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss.SSS");

long mills = LocalDateTime.parse(date,formatter)
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();

System.out.println(mills);

Java 8 LocalDateTime - How to keep .000 milliseconds in String conversion

LocalDateTime::toString omits parts if zero:

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

Use LocalDateTime::format instead of relying on toString().

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
LocalDateTime _120daysLater = LocalDateTime.parse("2016-10-17T12:42:04.000", formatter).minusDays(120);

// This just uses default formatting logic in toString. Don't rely on it if you want a specific format.
System.out.println(_120daysLater.toString());

// Use a format to use an explicitly defined output format
System.out.println(_120daysLater.format(formatter));

How to gain milliseconds of LocalTime variable?

TL;DR Use Duration, not LocalTime. See end of answer.


Question code is incorrect

Be aware that the 4th argument to LocalTime.of() is nanosecond, not millisecond, which you'd see if you print localTime:

System.out.println(localTime); // prints: 00:27:10.000000190

So you need to change your code to:

LocalTime localTime = LocalTime.of(0, minutes, seconds, milliseconds * 1000000);
System.out.println(localTime); // prints: 00:27:10.190

Using LocalTime

If you wanted the milliseconds value back, call getLong(TemporalField field) with ChronoField.MILLI_OF_SECOND:

localTime.getLong(ChronoField.MILLI_OF_SECOND) // returns 190

To gain total number of milliseconds, i.e. not just the milliseconds value, use ChronoField.MILLI_OF_DAY as argument:

localTime.getLong(ChronoField.MILLI_OF_DAY) // returns 1630190

Using Duration

However, since the input is named lapTime, the LocalTime class is not the right tool for the job. E.g. your code will fail if minutes >= 60.

The right tool is the Duration class, e.g.

Duration duration = Duration.ofMinutes(minutes).plusSeconds(seconds).plusMillis(milliseconds);

Or:

Duration duration = Duration.ofSeconds(seconds, milliseconds * 1000000).plusMinutes(minutes);

You can then get the milliseconds directly by calling toMillis():

duration.toMillis(); // returns 1630190

That works even if the lap time exceeds one hour, e.g.

String lapTime = "127:10.190";
. . .
duration.toMillis(); // returns 7630190

In Java 9+, you can get the millisecond part back easily, by calling toMillisPart():

duration.toMillisPart(); // returns 190

Java: time difference in milliseconds using LocalDateTime and ChronoUnit

I think the last param there is actually nano seconds:
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#of-int-java.time.Month-int-int-int-int-int-

Switching to a diff of nanos output 2 in my case:

LocalDateTime startDate = LocalDateTime.of(2017, 11, 22, 21, 30, 30, 250);
LocalDateTime endDate = LocalDateTime.of(2017, 11, 22, 21, 30, 30, 252);
long diff = ChronoUnit.NANOS.between(startDate, endDate);

System.out.println(diff);

Yields:

2

I think that since you are comparing millis, the diff is being rounded down.

LocalDateTime remove the milliseconds

Simply set them to 0:

myObj.setCreated(rs.getTimestamp("created").toLocalDateTime().withNano(0));

Sample/proof:

import java.time.LocalDateTime;

public class DateTimeSample {

public static void main(String[] args) {
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt);
System.out.println(ldt.withNano(0));
}
}

Output:

2015-07-30T16:29:11.684
2015-07-30T16:29:11

Author's note: Although this is the accepted one, Peter Lawrey's answer is IMHO preferrable because it makes the intention more clear.

Java 8 LocalDateTime.now() only giving precision of milliseconds

tl;dr

Is it possible to get microseconds in Java 8?

No, not in Java 8. Use Java 9 or later.

Instant.now()  // Returns a value in microseconds in Java 9 and later, but is restricted to mere milliseconds in Java 8.

This refers to the Oracle & OpenJDK implementations of Java 8/9. Others may vary.

Java 9 and later

The implementations of Java 9 based on OpenJDK have a fresh implementation of java.time.Clock capable of capturing the current moment in resolution finer than milliseconds (three digits of decimal fraction).

The actual resolution depends on the limits of your host computer hardware clock. On macOS Sierra with Oracle Java 9.0.4, I am getting current moment with microseconds (six digits of decimal fraction).

Instant.now().toString()

2018-03-09T21:03:33.831515Z

Java 8

The java.time classes were new in Java 8. These classes are defined to carry nanoseconds (nine digits of decimal fraction). But capturing the current moment was limited to only milliseconds in Java 8, and enhanced in Java 9 to capture the current moment in finer microseconds.

2018-03-09T21:03:33.831Z

Other issues

System.currentTimeMillis()

If I get System.currentTimeMillis() and System.nanoTime()

No need to use System.currentTimeMillis() ever again. Instead use java.time.Instant for a moment in UTC with a resolution as fine as nanoseconds.

If you really need a count of milliseconds from the epoch reference of 1970-01-01T00:00Z, ask the Instant object. Be aware of data loss, as you would be ignoring any microseconds or nanoseconds present in the Instant.

long millisSinceEpoch = instant.now().toEpochMilli() ;

Is there a way that I can parse clock time from these values?

Yes, you can convert a count of milliseconds since epoch of 1970-01-01T00:00Z to a Instant.

Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;

System.nanoTime()

As for System.nanoTime(), that is intended for tracking elapsed time, such as benchmarking your code’ performance. Calling System.nanoTime() does not tell you anything about the current date-time.

This value is a count of nanoseconds since some undocumented origin point in time. In practice, I have seen the number appear to track time since the JVM launched, but this behavior is not documented and so you should not rely upon it.

LocalDateTime is not a moment

My problem is that I need to do logging using both Java and Javascript and they need to have a consistent microsecond field across both of them.

Firstly, for logging you should not be using LocalDateTime class. That class purposely lacks any concept of time zone or offset-from-UTC. As such, a LocalDateTime does not represent a moment, is not a point on the timeline. A LocalDateTime is an idea about potential moments along a range of about 26-27 hours. Use LocalDateTime only if the zone/offset is unknown (not a good situation), or if this represents something like "Christmas Day starts on first moment of Decemeber 25, 2018", where Christmas starts at different moments for different regions around the globe, starting first in the far East (Pacific), and moving westward midnight after successive midnight.

For logging you should be using UTC. In Java, that would be the Instant class, always in UTC by definition. Just call Instant.now().

When serializing to text such as for logging, always use the standard ISO 8601 formats. The java.time classes use these standard formats by default when parsing/generating strings. You saw examples above in this Answer.

See another Question, What's the difference between Instant and LocalDateTime?.

Table of date-time types in Java, both modern and legacy

ISO 8601

In ISO 8601, the decimal fraction of a second can have any number of digits. So you really should not care about whether the logged event was recorded in milliseconds, microseconds, or nanoseconds.

Instant instant = Instant.parse( "2018-03-09T21:03:33.123456789Z" ) ;
Instant instant = Instant.parse( "2018-03-09T21:03:33.123456Z" ) ;
Instant instant = Instant.parse( "2018-03-09T21:03:33.123Z" ) ;

Truncate

If you really believe you need uniform resolution, you can truncate a Instant.

Instant instant = Instant.now().truncatedTo( ChronoUnit.MILLIS ) ; // Strip away any microseconds or nanoseconds.

Don't worry about resolution

My problem is that I need to do logging using both Java and Javascript and they need to have a consistent microsecond field across both of them.

Firstly, I doubt you really need to care about this. If you use standard ISO 8601 format, and the Instant class in Java, you can serialize and re-hydrate a moment successfully in millis, micros, or nanos.

And the ISO 8601 formatted strings will conveniently alphabetize chronologically even if the fractional second resolution varies.

Secondly, if you are trying to track actual moments to microseconds for some reason, you are likely to be disappointed. As of 2018, conventional computer clocks are not reliable in the microsecond range.



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, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 brought some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android (26+) bundle implementations of the java.time classes.
    • For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
      • If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….


Related Topics



Leave a reply



Submit