Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Joda LocalDateTime to Unix timestamp

How do I convert a org.joda.time.LocalDateTime to an Unix timestamp, given that local time is in UTC timezone?

Example:

new LocalDateTime(2015, 10, 02, 11, 31, 40) > 1443785500.

like image 314
Denis Kulagin Avatar asked Oct 02 '15 11:10

Denis Kulagin


1 Answers

Given that you want the Unix timestamp "the given LocalDateTime, in UTC" the simplest approach is just to convert it to a DateTime by specifying the DateTimeZone for UTC, and convert that:

LocalDateTime local = new LocalDateTime(2015, 10, 02, 11, 31, 40);
DateTime utc = local.toDateTime(DateTimeZone.UTC);
long secondsSinceEpoch = utc.getMillis() / 1000;

Note the use of seconds here as a Unix timestamp - other APIs (e.g. java.util.Date) may expect milliseconds since the Unix epoch.

like image 152
Jon Skeet Avatar answered Sep 22 '22 22:09

Jon Skeet