I have a variable containing time in seconds like 990
which would be 16 minutes 30 seconds. How do I convert this to time 00:16:30
in Groovy?
Along the same lines, how do I convert it the other way around?
String timestamp =
new GregorianCalendar( 0, 0, 0, 0, 0, 990, 0 ).time.format( 'HH:mm:ss' )
From duration to seconds:
long seconds = ( Date.parse( 'HH:mm:ss', '00:16:30' ).time -
Date.parse( 'HH:mm:ss', '00:00:00' ).time ) / 1000
assert
how would you store this calculation back in to a variable?
Take a look at this little creature below. Groovy's sprintf() and a bit of calculations. Unfortunately it doesn't look smart ;)
def seconds = 990
assert sprintf '%02d:%02d:%02d', (int) (seconds / 3600), (int) (seconds % 3600 / 60), (int) (seconds % 60) == '00:16:30'
Here You go:
def c = Calendar.instance
c.clear()
c.set(Calendar.SECOND, 990)
assert c.format('HH:mm:ss') == '00:16:30'
I suppose it might be done a bit smarter in plain groovy ;)
Once again, whole solution:
Calendar.instance.with {
clear()
set(Calendar.SECOND, 990)
assert format('HH:mm:ss') == '00:16:30'
def time = '00:16:30'.split(':')*.toInteger()
clear()
set(Calendar.MINUTE, time[1])
set(Calendar.SECOND, time[2])
assert (timeInMillis - Date.parse('HH:mm:ss', '00:00:00').time)/1000 == 990
}
with
. Calendar.instance.with { clear(); set(Calendar.SECOND, 990); format('HH:mm:ss') }
Commented
Jul 15, 2014 at 18:51
with
you don't need to specify Calendar.SECOND
or any of the other fields, just SECOND
or MINUTE
etc.