# How to use the Time package in Lua programming?

LuaServer Side ProgrammingProgramming

Lua library provides us with a time package that can be used to calculate the current time and that current time can be converted into hours, days and minutes and we can also take the later values and turn them into a Lua representation of time.

In order to make use of the library time package, we don’t necessarily need to require anything, we just need to write the following command in a Lua script and we are done.

Lua code for printing the current time in Lua format −

## Example

Live Demo

print(os.time())

## Output

1624642168

The output of the above time command definitely isn’t something that we normally expect when we talk about time, but this is how lua represents time, the number returned is basically a coded number which is a combination of current date and time.

## Example

Now that we know how to print the current coded date and time number, let’s encode it and convert it into hours and seconds.

Consider the code shown below −

local date = os.time()
local day2year = 365.242 -- days in a year
local sec2hour = 60 * 60 -- seconds in an hour
local sec2day = sec2hour * 24 -- seconds in a day
local sec2year = sec2day * day2year -- seconds in a year
-- year
print(date // sec2year + 1970) --> 2021.0
-- hour (in UTC)
print(date % sec2day // sec2hour)
-- minutes
print(date % sec2hour // 60)
seconds
print(date % 60)

## Output

2021.0
17
33
9
Updated on 20-Jul-2021 13:32:40