Convert number (90) to time format (00:01:30)

Here’s a script I found at macosxhints:

tell application "iTunes"
	set foo1 to name of current track
	set foo2 to player position
	set foo3 to duration of current track
	set foo4 to foo1 & " - " & foo2 & " of " & foo3
end tell

The code records time in seconds. What I’m trying to do is convert those seconds into time format eg 00:00:00. Is this possible? Thanks in advance.

div and mod are your friends…

You could probably do this with a series of divisions and mods. Assuming the number you get is in seconds something like this might work:


--origNUM is the number  in seconds
set numSeconds to origNUM mod 60
set temp to origNUM - numSeconds
set numMinutes to temp div 60
set numMinutes to numMinutes mod 60
set temp to (numMinutes * 60) + numSeconds
set temp to origNUM - temp
set numHours to temp div 3600
set finalTime to numHours & ":" & numMinutes & ":" & numSeconds as string

finalTime will have the format hh:mm:ss as a string. You can do whatever other formatting is needed

Dear DMC,

I did some improvement on your scritp:



--origNUM is the number  in seconds

set origNUM to 14569
set numSeconds to origNUM mod 60
set temp to origNUM - numSeconds
set numMinutes to temp div 60
set numMinutes to numMinutes mod 60
set temp to (numMinutes * 60) + numSeconds
set temp to origNUM - temp
set numHours to temp div 3600
if numHours < 10 then set numHours to "0" & numHours
if numMinutes < 10 then set numMinutes to "0" & numMinutes
set finalTime to numHours & ":" & numMinutes & ":" & numSeconds as string


Doesn’t it look better this way?

Using some cascading math, you could also do it via:


set origNUM to 14569
set numHours to origNUM div 3600
set numMinutes to (origNUM - (numHours * 3600)) div 60
set numSeconds to origNUM - (numHours * 3600) - (numMinutes * 60)
if numHours < 10 then set numHours to "0" & numHours
if numMinutes < 10 then set numMinutes to "0" & numMinutes
if numSeconds < 10 then set numSeconds to "0" & numSeconds
set finalTime to numHours & ":" & numMinutes & ":" & numSeconds as string

Hi,

Yes it’s better to start with the hours. Then you’re left with the seconds at the end. But instead of doing all the recalculations, you can use mod on the previous calculations:

–origNUM is the number in seconds

set origNUM to 14569
set numHours to origNUM div hours
set temp to origNUM mod hours
set numMinutes to temp div minutes
set numSeconds to temp mod minutes
if numHours < 10 then set numHours to “0” & numHours
if numMinutes < 10 then set numMinutes to “0” & numMinutes
set finalTime to numHours & “:” & numMinutes & “:” & numSeconds as string

gl,