inetphantom
inetphantom

Reputation: 2594

How to parse a timestamp with microseconds?

I want to parse a timestamp in and decrease it as less as possible (best would be one microsecond). It has the following format:

String source = "2018-15-05-23.59.59.999123"
String target = "2018-15-05-23.59.59.999122"

Now I can parse it like that: (see the docs here)

Date a = Date.parse("yyyy-MM-dd-HH.mm.ss.SSS","2018-15-05-23.59.59.999123");
        a.setTime(a.getTime()-1);
        a.format("yyyy-MM-dd-HH.mm.SSS000")}'

But this is parsing 123 for the milliseconds and I am loosing the microseconds: 2018-15-05-23.59.59.122000

Is there a way doing so?

Upvotes: 1

Views: 3131

Answers (2)

inetphantom
inetphantom

Reputation: 2594

As a workaround - this will cut at an accuracy from seconds and decrease by one millisecond (needed if timestamp would be 000000 - milliseconds)

'${Date a = Date.parse("yyyy-MM-dd-HH.mm.ss.","2018-15-05-23.59.59.999123");
        a.setTime(a.getTime()-1);
        a.format("yyyy-MM-dd-HH.mm.SSS999")}' 

What will evaluate to '2018-15-05-23.59.58.999999'

Upvotes: 0

Szymon Stepniak
Szymon Stepniak

Reputation: 42204

If you want to play with microseconds, use java.time.LocalDateTime instead. Consider following example:

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

String source = "2018-15-05-23.59.59.999123000"
String format = 'yyyy-dd-MM-HH.mm.ss.n'

LocalDateTime dateTime = LocalDateTime.parse(source, DateTimeFormatter.ofPattern(format))

println dateTime
println dateTime.minus(1, ChronoUnit.MICROS)

Output:

2018-05-15T23:59:59.999123
2018-05-15T23:59:59.999122

The java.util.Date case

When playing with java.util.Date you are limited to milliseconds. Take a look at this example:

String source = "2018-15-05-23.59.59.999123"
String format = 'yyyy-dd-MM-HH.mm.ss.SSSSSS'

def date = Date.parse(format, source)
println date.format(format)

What gets printed to the console?

2018-16-05-00.16.38.000123

Milliseconds are limited to 3 characters length and 999123 milliseconds are equal to 16.65205 minutes.

Upvotes: 1

Related Questions