Khilarian
Khilarian

Reputation: 251

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

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.

Upvotes: 3

Views: 1468

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40078

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);

Upvotes: 5

Basil Bourque
Basil Bourque

Reputation: 339432

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() ;

Upvotes: 2

Related Questions