# Converting to 12 hour time not working?

I’m trying to convert the `Lighting.TimeOfDay` into 12-hour time. From enough browsing on the DevForum, I’ve created a simple function that looks like this:

``````local function ConvertTo12Hour(Time)

local minutes = string.sub(Time, 4, 5) -- Gets the minutes, keeps the extra 0

local hourRaw = tonumber(Time:match("^%d+"))
local hour12h = math.floor(hourRaw % 12)
local isPM = (hour12h / 12) >= 1

if hour12h == 0 then
hour12h = 12
end

local formattedTime = ("%d:%d %s"):format(hour12h, minutes, isPM and "PM" or "AM")
return formattedTime
end
``````

But for some reason, the minutes always appears without the 0 in front of it on a TextLabel. For instance, I would like it to say “11:05,” but in this case it would only show up as “11:5.” Why is this not working correctly?

2 Likes

By the way, the `Time` that I’m inputting is just the standard `Lighting.TimeOfDay`.

Try this out?

``````local formattedTime = ("%02d:%02d %s"):format(hour12h, minutes, isPM and "PM" or "AM")
``````

So that way if the number is than 2 digits, it’ll pad the left side with zeroes

2 Likes

Thanks! It works perfectly. I’m not great with string manipulation. To anyone reading this thread in the future, my code is:

``````local function ConvertTo12Hour(Time)

local minutes = string.sub(Time, 4, 5)
local hourRaw = tonumber(Time:match("^%d+"))
local hour12h = math.floor(hourRaw % 12)
local isPM = (hour12h / 12) >= 1

if hour12h == 0 then
hour12h = 12
end

local formattedTime = ("%d:%02d %s"):format(hour12h, minutes, isPM and "PM" or "AM")
return formattedTime
end
``````

Where `Time` should be `Lighting.TimeOfDay`

1 Like

Anytime! If you have anymore issues don’t be afraid to make another post!