Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

long timestamp to LocalDateTime

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()); 
like image 590
rhandom Avatar asked Jul 03 '17 10:07

rhandom


People also ask

How do I set timestamp in LocalDateTime?

LocalDateTime ldt = new LocalDateTime(); DateTimeFormatter dtf = DateTimeFormatter. forPattern("yyyy-MM-dd HH:mm:ss"); Timestamp ts = Timestamp. valueOf(ldt. toString(dtf));


2 Answers

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 
like image 159
Juan Avatar answered Oct 13 '22 19:10

Juan


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.

like image 41
Akshay Avatar answered Oct 13 '22 19:10

Akshay