3

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?

0

3 Answers 3

3
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
5
  • Im not too familiar with assert how would you store this calculation back in to a variable?
    – Brian
    Commented Jul 15, 2014 at 18:07
  • Updated answer. Second approach to convert timestamp to seconds can be moved to a method to make it DRYier. I just tried to showcase the gist.
    – dmahapatro
    Commented Jul 15, 2014 at 18:09
  • I'm barely diving into the language, keeping things DRY at this point is way over my head. haha
    – Brian
    Commented Jul 15, 2014 at 18:11
  • Used Groovy assert earlier to show expected == actual.
    – dmahapatro
    Commented Jul 15, 2014 at 18:13
  • Not a problem, take your time and stay groovy. ;)
    – dmahapatro
    Commented Jul 15, 2014 at 18:14
2

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'
2

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
}
3
  • This can be optimized a bit with use of with. Calendar.instance.with { clear(); set(Calendar.SECOND, 990); format('HH:mm:ss') }
    – dmahapatro
    Commented Jul 15, 2014 at 18:51
  • I haven't noticed it! ;] Thanks for the clue! I like the clues You give!
    – Opal
    Commented Jul 16, 2014 at 6:55
  • This is very nitpicky - but also in your with you don't need to specify Calendar.SECOND or any of the other fields, just SECOND or MINUTE etc.
    – Alex
    Commented Feb 18, 2020 at 18:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.