  Android Question Convert seconds to HH MM SS and then back again

Discussion in 'Android Questions' started by aaronk, Apr 19, 2015.

1. Hi,

I can't seem to work out how to convert a value that constants only seconds to Hours, Minutes, Seconds.

For example:
Convert 1242 seconds to:
Hours = 00
Minutes = 20
Seconds = 42

Then I want to be able to convert it the other way around:
Hours, Minutes, Seconds = xx Seconds

Anyone able to help ?

2. Code:
Sub calchourstring(old As Int) As String

'Log("int 1242 0h 20m 42s")
Dim h As Int = Abs(old/3600)

Log(h)

Dim m As Int = Abs((old-(h*3600))/60)

Log(m)

'Log("test "&((h*3600)+(m*60)))
Dim s As Int = Abs(   old-((h*3600)+(m*60))         )

Log(s)

Return NumberFormat(h,2,0)&":"&NumberFormat(m,2,0)&":"&NumberFormat(s,2,0)
End Sub
Sub calcseconds(hourstring As StringAs Int

Dim c() As String =Regex.Split(":",hourstring)

Return (c(0)*3600)+(c(1)*60)+c(2)
End Sub

Log(calchourstring(1242))
Log(calcseconds(calchourstring(1242)))

MarcoRome and Peter Simpson like this.
3. Or:
Code:
Sub calchourstring(old As Int) As String

'Log("int 1242 0h 20m 42s")
Dim s As Int = old Mod 3600 'seconds without hours
Dim h As Int = old/3600 'no Abs() needed because stored in Int variable
Dim m As Int = s/60
s = s
Mod 60

Log(h)

Log(m)

Log(s)

Return NumberFormat(h,2,0)&":"&NumberFormat(m,2,0)&":"&NumberFormat(s,2,0)
End Sub

DonManfred likes this.
4. So wollte ich eigentlich auch vorgehen, hatte aber irgendwie einen Denkfehler und löste es dann anders 5. Thanks heaps for your help with this.. Something so simple but just couldn't work it out.. one of those nights.

6. I want to convert decimals (ex 2.75 = 2 hrs 45 mn)

I do not understand the error ! (02 hours, 02 minutes and 165 seconds)

Code:
Dim finalBuildTime As Double = 2.75

Dim hours, minutes, seconds  As Int
hours =  finalBuildTime
minutes = (finalBuildTime *
60) / 60
seconds = (finalBuildTime * (
60*60))/ 60
LogColor(
NumberFormat(hours, 20) & " hours, " & NumberFormat(minutes, 20) & " minutes and " & NumberFormat(seconds, 20) & " seconds"Colors.Blue)

Last edited: Aug 19, 2017
7. it's ok

Code:
Dim finalBuildTime As Double = 2.75

Dim hours, minutes, seconds  As Int
hours =  finalBuildTime
minutes = (finalBuildTime - hours)*
60
seconds = (finalBuildTime - hours)*
3600 - minutes * 60 +0.5
LogColor(
NumberFormat(hours, 20) & " hours, " & NumberFormat(minutes, 20) & " minutes and " & NumberFormat(seconds, 20) & " seconds"Colors.Blue)

8. ABS = Absolute Number, i guess you meant "Floor"!! i would recommend to work with ticks whenever you want to get time/date.

so this could be also a possibility:

Code:
Dim seconds As Int = 1242 * DateTime.TicksPerSecond 'convert seconds to ticks!
Log("Days: " & Floor(seconds/DateTime.TicksPerDay))
Log("Hours: " & Floor(seconds/DateTime.TicksPerHour Mod 24))
Log("Minutes: " & Floor(seconds/DateTime.TicksPerMinute Mod 60))
Log("Seconds: " & Floor(seconds/DateTime.TicksPerSecond Mod 60))

Last edited: Aug 19, 2017