Home > Blockchain >  Subtract number of hours from current time in Java
Subtract number of hours from current time in Java

Time:06-05

I have a string that represents time duration of 54:34:41 i.e. 54 hours, 34 minutes, 41 seconds.

I would like to extract the 54 hours and subtract it from the current system time.

However when I run below I get java.time.format.DateTimeParseException: Text '54:34:41' could not be parsed: Invalid value for HourOfDay (valid values 0 - 23): 54

How can I extract 54 hours and subtract from current time?

private val formatterForTime: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss")
val timeDuration = formatterForTime.parse("54:34:41")

val currentTime = LocalDateTime.now()
val newTime = currentTime.minusHours(timeDuration.get(ChronoField.HOUR_OF_DAY).toLong())

CodePudding user response:

tl;dr

ZonedDateTime
.now( 
    ZoneId.of( "Asia/Tokyo" ) 
)
.minusHours(
    Integer.parseInt( "54:34:41".split( ":" )[0] )
)

Details

Parse hours

Get the number of hours.

int hours = Integer.parseInt( "54:34:41".split( ":" )[0] ) ;

ISO 8601

Your input text for a span-of-time does not comply with the ISO 8601 standard for date-time values. The java.time classes by default use the standard formats when parsing/generating text.

If instead of 54:34:41 you had PT54H34M41S, then we could use:

int hours = Duration.parse( "PT54H34M41S" ).toHours() ;

I recommend you stick with the standard format rather than the ambiguous clock-time format.

Capture current moment

Capture the current moment as seen in a particular time zone.

ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

Subtract hours

Subtract your hours.

ZonedDateTime earlier = zdt.minusHours( hours ) )
  • Related