26

Currently, to get milliseconds from start of 1970 in a local time zone, I do

long localMillis = dateTime.withZone(timeZone).toLocalDateTime()
    .toDateTime(DateTimeZone.UTC).getMillis();

This works, but is there a simpler way to do this?

3
  • I'm not sure I understand why you'd want to do this. The getMillis method on all ReadableInstant types is independent of the DateTime's time zone, and always returns the number of milliseconds passed since the epoch (midnight Jan 1, 1970, UTC). Are you saying you want the number of milliseconds passed since midnight Jan 1, 1970 in a non-UTC time zone? (e.g. PST, CEST, etc). If so, why would you want this? Jul 29, 2012 at 16:21
  • @AndrewMcNamee Yes, that's the number I want, because that's how dates are stored in an external database I need to access. Yes, it's a bad way to store them, but it can't be changed. Jul 29, 2012 at 19:18
  • Ah, fair enough. Yep, definitely less than ideal, but if it can't be changed, it can't be changed (just be sure to document it thoroughly ;) ). I have a slightly clearer suggestion. Will write it as an answer in a sec. Jul 30, 2012 at 12:16

2 Answers 2

16

You can make this a little clearer by storing a constant LocalDateTime referring to Jan 1, 1970, and then calculating a Duration between that point in time (for a given time zone) and the instant that you care about, like:

private static final LocalDateTime JAN_1_1970 = new LocalDateTime(1970, 1, 1, 0, 0);

...

new Duration(JAN_1_1970.toDateTime(someTimeZone), endPointInstantOrDateTime).getMillis();
5

Use (joda-time-2.3.jar) org.joda.time.LocalDateTime#toDateTime()#getMillis().

org.joda.time.format.DateTimeFormatter dtf = org.joda.time.format.DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
org.joda.time.LocalDateTime ldt = dtf.parseLocalDateTime("2014-12-25 12:23:34.567");
System.out.println(ldt);

long delta = ldt.toDateTime().getMillis();
System.out.println(delta);

java.util.Date dt = new java.util.Date(delta);
System.out.println(dt);
2
  • 1
    This does not answer the OP's question, on two counts. First, his question, and the accepted answer by Andrew McNamee, are based on the local time being specified by a DateTime object. Your answer assumes use of a LocalDateTime object as the starting point. Second, the OP's question and the accepted answer are independent of the system's time zone, while your answer is dependent on the system's time zone.
    – RenniePet
    Mar 9, 2015 at 22:59
  • 1
    For example, for Jan. 2, 1970 at 00:00, the OP and Andrew McNamee get 86400000 millis, and you get 82800000 for my Copenhagen-based system.
    – RenniePet
    Mar 9, 2015 at 22:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.