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);
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();
long timestamp to LocalDateTime
You need to pass timestamp in milliseconds:
long test_timestamp = 1499070300000L;
LocalDateTime triggerTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp),
TimeZone.getDefault().toZoneId());
System.out.println(triggerTime);
Result:
2017-07-03T10:25
Or use ofEpochSecond
instead:
long test_timestamp = 1499070300L;
LocalDateTime triggerTime =
LocalDateTime.ofInstant(Instant.ofEpochSecond(test_timestamp),
TimeZone.getDefault().toZoneId());
System.out.println(triggerTime);
Result:
2017-07-03T10:25
How to extract epoch from LocalDate and LocalDateTime?
The classes LocalDate
and LocalDateTime
do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId
instance.
LocalDate
LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();
LocalDateTime
LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();
LocalDate to Epoch by Ignoring DayLightSaving
By Ignoring timezone below code will do the job for you
localDate.atStartOfDay().atOffset(UTC).toEpochSecond()
Or Maybe you need this:
TimeZone timeZone = TimeZone.getTimeZone("GMT+1");// Paris timezone without daylight saving
localDate.atStartOfDay(timeZone.toZoneId()).toEpochSecond();
The idea is to use a fixed zone offset to get rid of daylight saving.
Java 8 epoch-millis time stamp to formatted date, how?
An Instant
does not contain any information about the time-zone, and unlike in other places, the default time-zone is not automatically used. As such, the formatter cannot figure out what the year is, hence the error message.
Thus, to format the instant, you must add the time-zone. This can be directly added to the formatter using withZone(ZoneId)
- there is no need to manually convert to ZonedDateTime
*:
ZoneId zone = ZoneId.systemDefault();
DateTimeFormatter df = DateTimeFormatter.ofPattern("...pattern...").withZone(zone);
df.format(Instant.ofEpochMilli(timestamp))
* regrettably, in early Java 8 versions, the DateTimeformatter.withZone(ZoneId)
method did not work, however this has now been fixed, so if the code above doesn't work, upgrade to the latest Java 8 patch release.
Edit: Just to add that Instant
is the right class to use when you want to store an instant in time without any other context.
Related Topics
Are There Best Practices for (Java) Package Organization
Performance of Javafx Gui VS Swing
Please Explain About Insertable=False and Updatable=False in Reference to the JPA @Column Annotation
Why Do We Need Copy Constructor and When Should We Use Copy Constructor in Java
Jtable Won't Show Column Headers
Stack with Find-Min/Find-Max More Efficient Than O(N)
Do Any Jvm's Jit Compilers Generate Code That Uses Vectorized Floating Point Instructions
How to Insert a Character in a String at a Certain Position
Java: How to Indent Xml Generated by Transformer
How to Get All Table Names from a Database
How to Monitor Java Memory Usage
Java 'File.Delete()' Is Not Deleting Specified File
Variable Naming Conventions in Java