Skip to content
Advertisement

How to parse time based tokens in java ?(1m 1M 1d 1Y 1W 1S)

I gets following strings from FE:

JavaScript

It corresponds to 1 minute, 5 months,3 days, 30 minutes, 2 hours, 1 year, 3 weeks.

Is there mean in java to parse it?

I want to manipulate(add/minus) with Instant(or LocalDatetTime). Is there way to do it in java?

Advertisement

Answer

Period & Duration

I consider the following solution simple and pretty general (not fully general).

JavaScript

It seems that your date-based units (year, month, week, day) are denoted with uppercase abbreviations (Y, M, W and D) while the time-based ones (hour and minute) are lowercase (h and m). So I test the case of the last character of the string to decide whether to parse into a Period or a Duration. I exploit the fact that both of Period.parse and Duration.parse accept the letters in either case.

You wanted to add or subtract the durations to and from Instant or LocalDateTime. This works in most cases. Let’s see:

JavaScript

Output:

JavaScript

We see that adding to LocalDateTime works in all cases. Adding to Instant works in most cases, only we cannot add a period of months or years to it.

Advertisement