Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to use os.time() & os.date() and what it does?

Asked by 5 years ago

ROBLOX's developer wiki gives some basic information on it (os.date() used to get days/months/years, os.time() can be used to get user's current real life time) however it does not give a lot of information on how to use it.

It would be very helpful if somebody could point me in the right direction on how it works, how to use it, and maybe go more in depth about what each of them do.

1 answer

Log in to vote
7
Answered by
chomboghai 2044 Moderation Voter Community Moderator
5 years ago
Edited 5 years ago

Using os.time() is pretty straight forward, like it says in the wiki:

Returns how many seconds since the epoch (1 January 1970, 00:00:00), under UTC time.

Example usage:

print("It has been " .. os.time() .. " seconds since the epoch.")

os.time() also has an optional parameter. You can input a dateTable ( essentially a date and time in the form of a table, will get to more on it later ) to get how many seconds since the epoch up until that date.

os.date() is a little different and much more useful. It has two parameters. The first is the format string which determines if you want the date in local time or in UTC by inputting either "*t" or "!*t" respectively. The second parameter is the number of seconds from epoch. This is where os.time() is useful. If you want to get the current dateTable, you can use os.time() as the second input.

This function returns a dateTable, which is actually just a table but organized in a specific way.

Here is an example usage of os.date() as well as the format of the dateTable it returns.

local dateTable = os.date("*t", os.time()) -- gets the current date in local time

-- taking a look inside dateTable:
dateTable = {
    year: 2018
    month: 8
    wday: 5 -- the current weekday starting from Sunday
    yday: 235 -- the number of days we are into the year (ranges from 1-365 or 366 if leap year) 
    day: 23 -- current day of the month
    hour: 12 -- values from 1-24
    min: 0
    sec: 0
    isdst: true -- is daylight savings on?
}

-- Making a table to convert wday to the word format.
local days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}

-- Now you can simply use the dateTable like a regular table.
local message = string.format("Today is %s and it is d:d right now.", days[dateTable.wday], dateTable.hour, dateTable.min)

print(message) --> "Today is Thursday and it is 12:00 right now."

I hope this gives you an understanding of os.time() and os.date()!

0
Thank you, this helped a ton! momentoflua 2 — 5y
0
nice Vulkarin 581 — 5y
Ad

Answer this question