How to create a long time in Milliseconds from String in Java 8 with LocalDateTime?

一笑奈何 提交于 2020-02-02 04:59:45

问题


I have an input date in format yyyy-MM-dd_HH:mm:ss.SSS and convert it to long this way:

SimpleDateFormat simpleDateFormat = 
                   new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");
try {
    Date date = simpleDateFormat.parse(lapTime);
    time = date.getTime();
} catch (ParseException e) {
    e.printStackTrace();
}

And, after some manipulation, get mm:ss.SSS back from long:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss.SSS");
return simpleDateFormat.format(new Date(time));

How to change my old style code to Java8? I looked at LocalDateTime and Instant classes, but don't know how to use them properly.


回答1:


You can create DateTimeFormatter with input formatted date and then convert into Instant with zone to extract epoch timestamp

String date = "2019-12-13_09:23:23.333";
DateTimeFormatter formatter = 
         DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss.SSS");

long mills = LocalDateTime.parse(date,formatter)
                .atZone(ZoneId.systemDefault())
                .toInstant()
                .toEpochMilli();

System.out.println(mills);



回答2:


tl;dr

LocalDateTime
.parse(
    "2019-12-13_09:23:23.333".replace( "_" , "T" )
)
.atZone(
    ZoneId.of( "Africa/Casablanca" ) 
)
.toInstant()
.toEpochMilli() 

ISO 8601

Your input string is close to compliance with the standard ISO 8601 formats used by default in the java.time classes when parsing/generating strings.

To fully comply, simple replace the underscore _ I. The middle with a uppercase T.

String input =  "2019-12-13_09:23:23.333".replace( "_" , "T" ) ;

Parse without needing and formatter.

LocalDateTime ldt = LocalDateTime.parse( input ) ;

Assign the time zone intended for this date and time. Did the publisher of that data intend 9 AM in Tokyo Japan on that date, or did they mean 9 AM in Toledo Ohio US? Those would be two different moments several hours apart.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

Extract an Instant to adjust into UTC. Interrogate for the count of milliseconds since first moment of 1970 in UTC.

long milliseconds = zdt.toInstant().toEpochMilli() ;


来源:https://stackoverflow.com/questions/59329786/how-to-create-a-long-time-in-milliseconds-from-string-in-java-8-with-localdateti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!