Lua - Date & Time



Lua provides following functions to do all operations on date and time like getting formatted dates, date manipulations, getting current time, getting time differences etc.

  • date()− This function is used to get formatted date, current date

  • time()− This function is used to get a particular timestamp as per provided arguments

  • clock()− This function provides the CPU clock time and can be used to compute execution time

  • difftime()− This utility function can be used to get difference between two timestamps in seconds

Following examples showcase various scenarios.

Example - Get Current Date and Time

A simple example to get current date and time is shown below.

main.lua

-- get the system current date and time
currentDate = os.date()
-- print the date
print(currentDate)

Output

When we run the above program, we may get the similar output.

Wed Oct 16 09:28:49 2024

Example - Get Formatted Date

A simple example to get formatted date is shown below.

main.lua

-- get the formatted date
formattedDate = os.date("%d-%m-%Y")
-- print the date
print(formattedDate)

Output

When we run the above program, we may get the similar output.

15-10-2024

Format Codes

To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following −

Character Description Example
a Abbreviated weekday name Wed
A Full weekday name Wednesday
b abbreviated month name Sep
B full month name September
c date and time 09/16/98 23:48:10
d day of the month (16)[01-31]
H hour, using a 24-hour clock (23) [00-23]
I hour, using a 12-hour clock (11) [01-12]
M minute (48) [00-59]
m month (09) [01-12]
p either "am" or "pm" (pm)
S second (10) [00-61]
w weekday (3) [0-6 = Sunday-Saturday]
x date 09/16/98
X time 23:48:10
Y full year 1998
y two-digit year (98) [00-99]
% the character `%´ %

Example - Get Difference in seconds

A simple example to get timestamps and difference between them is shown below.

main.lua

-- define and get a date
time1 = os.time({year = 2024, month = 9, day = 15, hour = 8, min = 0})
- define another date
time2 = os.time({year = 2024, month = 9, day = 15, hour = 9, min = 0})
-- compute the difference between two dates
diff = os.difftime(time2, time1)
-- print the difference
print("Time difference:", diff, "seconds")

Output

When we run the above program, we will get the following output−

Time difference:	3600.0	seconds

Example - Getting execution time

A simple example to get execution time of any time consuming process is shown below.

main.lua

-- CPU Start Time
startTime = os.clock()

-- a time-consuming task
for i = 1, 10000000 do
   math.sqrt(i)
end

-- CPU End Time
endTime = os.clock()

-- Print the elapsed time
print("Elapsed CPU time:", endTime - startTime, "seconds")

Output

When we run the above program, we may get the similar output.

Elapsed CPU time:	0.225313	seconds
Advertisements