The second argument of os.date is the time in seconds since the UNIX Epoch in which os.date should work off of. If you do not specify this argument, it defaults to the value of os.time.
local DATE_FORM = "%d/%d/%d"
local DATE_0 = os.date("!*t", 0)
print(DATE_FORM:format(DATE_0.day, DATE_0.month, DATE_0.year)) -- 1/1/1970
So, we’re going to use this argument to our advantage. Work in UTC time so that you can ensure a reasonable time, since the returned time isn’t exactly consistent across servers. Now remember that timezones are based on UTC as an offset of it.
Recall what EST is in terms of UTC: UTC-5. Eastern Standard Time (EST, UTC-5) is 5 hours behind Coordinated Universal Time (UTC). 5 hours is 18000 seconds (3600 seconds in an hour * 5 hours). This will be our offset from the current time.
local EST_SECONDS = os.time() - 18000
os.time is fetched as the number of seconds since the UNIX Epoch which is January 1st, 1970, in terms of UTC. So we offset it 5 hours back. This will serve as our time value. Now all that’s left is to plug it right into os.date which will send us back a dictionary of information about the given time.
local EST_SECONDS = os.time() - 18000 -- or os.time() - (3600*5)
local EST_DATE = os.date("!*t", EST_SECONDS)
local EST_MONTH = EST_DATE.month
print(EST_MONTH) -- 12
And there you are. The date in EST.
To summarise, here are the key concepts to take away:
- The os library works in UTC unless able to specify otherwise (
*t
for os.date).
- All timezones are an offset of UTC forward or backward by some hours
- You must convert the hour offset into seconds to work with os.time properly
- With the number you get above, add or subtract it from os.time to get the seconds in a certain timezone (for EST, it’s back 5 hours, so take away 5 hours in seconds from os.time)
- Plug the number of seconds into the second argument of os.date so that it will form a date table based off of the seconds given
Fun fact: You can reverse this operation too. os.time accepts a date table argument (not documented), so if you know the exact information of these dates, you can retrieve the value of os.time for a specific date as well.