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?

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • 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? – Andrew McNamee Jul 29 '12 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. – Alexey Romanov Jul 29 '12 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. – Andrew McNamee Jul 30 '12 at 12:16

2 Answers2

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();
Andrew McNamee
  • 1,705
  • 1
  • 13
  • 11
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);
Ethan Lee
  • 79
  • 1
  • 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 09 '15 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 09 '15 at 22:59