How to convert the number of the day of the week to the name of the day of the week?

Hi, I am trying to convert the number of the day of the week to the name of the day of the week.

This is what I did so far, but the problem is that it doesn’t work if you put a number higher than 7.

local function formatDay(day: number)
	local days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
	return days[day]
end

print(formatDay(2)) --> Tuesday

Try this:

formatDay(n-(math.floor(n/7)*7))

This won’t work either because lua tables start at 1 and not 0 (any multiple of 7 would give 0). They’d have to change the function as well to have the first index be 0 and treat it as such everywhere else.

:thinking: I tested my solution before replying, and it works.

Here it is, working as expected:
image

local function formatDay(day: number)
    local days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

    return days[day % 7 ~= 0 and day % 7 or 7]
end

print(formatDay(14)) --> Sunday

is this what you want?

2 Likes

actually your solution is not perfect, you pretty much remade modulo(%)

if the number is divisible by 7 it will be 0 not 7
just wanted to let you know