10

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.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Denis Kulagin
  • 8,472
  • 17
  • 60
  • 129
  • If I recall, Unix timestamp is the number of seconds since the Unix epoch, maybe something like [this](http://stackoverflow.com/questions/22990067/how-to-extract-epoch-from-localdate-and-localdatetime) – MadProgrammer Oct 02 '15 at 11:34
  • 1
    A `LocalDateTime` doesn't have a time zone, so it doesn't represent one ponit in time. You need to specify a time zone in order for that to make any sense. – Jon Skeet Oct 02 '15 at 11:34
  • @MadProgrammer That's link is about Java 8 time api, not Joda! Unfortunatelly I haven't found the same thread for Joda l.d.t. – Denis Kulagin Oct 02 '15 at 11:39
  • @DenisKulagin Opps, was a quick search :P – MadProgrammer Oct 02 '15 at 12:05
  • @MadProgrammer N.P., I've also encountered those question and even tried to put it in code. No luck, obviously) – Denis Kulagin Oct 02 '15 at 13:07

1 Answers1

22

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Also you can use `DateTimeConstants.MILLIS_PER_SECOND` instead of `1000` or use `Duration.millis(local.toDateTime(DateTimeZone.UTC).getMillis).getStandardSeconds`. – mixel Jun 19 '16 at 20:21
  • Simple and neat, When the Joda developer is making out reasons to expose getLocalMillis() as public. Link: https://github.com/JodaOrg/joda-time/issues/87 – vijay May 18 '17 at 15:14