Simplest way to get local milliseconds in a time zone with Joda-Time

后端 未结 2 391
孤街浪徒
孤街浪徒 2020-12-16 10:22

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

long localMillis = dateTime.withZone(timeZone).toLocalDateTime()
    .toDateTime         


        
相关标签:
2条回答
  • 2020-12-16 10:53

    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();
    
    0 讨论(0)
  • 2020-12-16 11:00

    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);
    
    0 讨论(0)
提交回复
热议问题