How to convert seconds to hⓂs and d:h:m:s

How do I convert seconds to hours, minutes, seconds and days, hours, minutes, seconds

1 Like

Use some extremely simple math.

local seconds = 242
local mins = seconds/60
local hours = mins/60
local days = hours/24

And to reverse:

local days = 83
local hours = days*24
local mins = hours*60
local seconds = mins*60
1 Like

Let “s” be seconds.

Minutes = 60*s
Hours = 60*60*s
Days = 24*60*60*s

Simply reverse the operations and divide if you’re going the other way around

But then it will display 242 seconds

242 was just an example, you don’t need that.

Ik but I am talking about using os.time and getting a bigger number that I later use to get the hrs mins and secs

Here, use this function.

local function toDHMS(s)
	return ("%i:%02i:%02i:%02i"):format(s/60^2/24, s/60^2, s/60%60, s%60)
end

local seconds = 283
toDHMS(seconds)
2 Likes

https://developer.roblox.com/en-us/api-reference/lua-docs/os

Use the os.difftime() function.

1 Like
local function SecondsToString(seconds)
    local days = math.floor(seconds / 86400)
    local hours = math.floor(seconds % 86400 / 3600)
    local minutes = math.floor(seconds % 3600 / 60)
    seconds = math.floor(seconds % 60)
    return string.format("%d:%02d:%02d:%02d", days, hours, minutes, seconds)
end
3 Likes

How about seconds to HMS? Hours, minutes, seconds

For HMS:

local function toHMS(s)
	return ("%02i:%02i:%02i"):format(s/60^2, s/60%60, s%60)
end

local seconds = 283
toHMS(seconds)

@Philipceo90

Use this instead:


local function toHMS(s)
	return ("%02i:%02i:%02i"):format(s/60^2, s/60%60, s%60)
end

local seconds = 283
toHMS(seconds) — toDHMS -> toHMS

That’s the same thing… it’s the same exact script.

No, you said toDHMS() instead of toHMS(), and then changed it right when I corrected you

I must have edited right when you posted that

Probably so.

filler wordhereqjeriwnq

How would I add months years also where do u find all this info

A long time ago when I needed it I searched the DevForum and found that. It’s just some basic string manipulation that you can learn off the DevHub.

You can use os.date() (you could actually use the for h:m:s and d:h:m:s aswell)

local curDateInSeconds = os.time()
local seconds = 35869214
local formatted = os.date("!%Y:%m:%H:%M:%S", (curDateInSeconds + seconds))

print(formatted) --2023:09:19:03:21
1 Like

could i use string.format tho cause i use tick() as os.time doesnt work properly for some reason

They’re not the same thing. Format only allows you to insert variables into a string. You just need to keep dividing or multiplying depending on which direction you need to go.