long timestamp to LocalDateTime
112,703
Solution 1
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
Solution 2
Try with the following..
long test_timestamp = 1499070300000L;
LocalDateTime triggerTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp), TimeZone
.getDefault().toZoneId());
By default 1499070300000
is int if it dosen't contain l in end.Also pass time in milliseconds.
Solution 3
If you are using the Android threeten back port then the line you want is this
LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault())
Solution 4
Try with Instant.ofEpochMilli()
or Instant.ofEpochSecond()
method with it-
long test_timestamp = 1499070300L;
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp ), TimeZone
.getDefault().toZoneId());
Solution 5
Your issue is that the timestamp is not in milliseconds but expressed in seconds from the Epoch date. Either multiply by 1000 your timestamp or use the Instant.ofEpochSecond()
.
Related videos on Youtube
Comments
-
rhandom over 2 years
I have a long timestamp 1499070300 (equivalent to Mon, 03 Jul 2017 16:25:00 +0800) but when I convert it to LocalDateTime I get 1970-01-18T16:24:30.300
Here's my code
long test_timestamp = 1499070300; LocalDateTime triggerTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp), TimeZone .getDefault().toZoneId());
-
Akshay almost 7 yearslong test_timestamp = 1499070300l;??
-
JodaStephen almost 7 yearsUse
ZoneId.systemDefault()
instead ofTimeZone.getDefault().toZoneId()
-
Ole V.V. almost 7 yearsYou’re not the first to ask a about a bug like this one. For example: SimpleDateFormat always returns 1970.01.17 with wrong timezone.
-
Basil Bourque almost 5 years
-
-
Andy Turner almost 7 yearsYou mean "Try with Instant.ofEpochSecond()", right? Otherwise your text is confusing.
-
rhandom almost 7 yearsThanks. I missed that
-
Louis Tsai about 6 yearsBTW if you are using AndroidThreeTen, replace
TimeZone.getDefault().toZoneId()
withDateTimeUtils.toZoneId(TimeZone.getDefault())
.