New timestamp class
Posted: Thu Jan 01, 2015 1:53 pm
Time is something we work with very often in our scripts, but has historically been a bit of a bother to manage cleanly. So, today, I decided to write up a class to handle it that is roughly based off Carbon for PHP.
To use this module, you need to require it at the top of your main script like so:
This new class, Timestamp, supports method-chaining. That is, function calls to modify its time value will return a new object instead of actually modify the calling object. This means we can do something like this:
This will give us a Timestamp object that is 'now' plus an hour and a half. It also supports adding/subtracting everything else you could want: seconds, days, months, years. You can also create arbitrary timestamps for any date and time you can think of. Or get the timestamp for now, today, yesterday, or tomorrow.
Here's an example:
Output:
When adding/subtracting months, it properly keeps track of how many days are in each month instead of just assuming some number. If you add/subtract any number that overflows its bounds (such as adding 13 months when there are only 12 in a year), it will also increment the required fields.
The isPast() method will be quite handy. Very often we want to trigger some event(s) after some time has past. Instead of:
We can simply:
What other features do you think could be useful?
To use this module, you need to require it at the top of your main script like so:
Code: Select all
require('timestamp');
Code: Select all
local later = Timestamp:now():addhours(1):addMinutes(30);
Here's an example:
Code: Select all
local now = Timestamp:now();
print("Now:\t", now);
local past = now:subSeconds(30);
print("-30 sec:", past);
print("\t\tIs past?", past:isPast(), past:diffForHumans(), "\n");
local later = now:addHours(12):addMinutes(90):addSeconds(32);
print("Later:\t", later);
local today = Timestamp:today();
print("Today:\t", today);
local yesterday = Timestamp:yesterday();
print("Yesterday:", yesterday);
local nextMonth = now:addMonths(1);
print("Next month:", nextMonth);
local arbitrary = Timestamp(2016, 6, 12, 8, 52);
print("Arbitrary:", arbitrary);
print("Year-month:", arbitrary:format("%Y-%m"));
print("Now less than arbitrary?", now < arbitrary);
Code: Select all
Now: 2015-01-01 12:38:51
-30 sec: 2015-01-01 12:38:21
Is past? true 30 seconds ago
Later: 2015-01-02 02:09:23
Today: 2015-01-01 00:00:00
Yesterday: 2014-12-31 00:00:00
Next month: 2015-02-01 12:38:51
Arbitrary: 2016-06-12 08:52:00
Year-month: 2016-06
Now less than arbitrary? true
The isPast() method will be quite handy. Very often we want to trigger some event(s) after some time has past. Instead of:
Code: Select all
doSomethingTimestamp = os.time() + 3;
...
if( os.time() > doSomethingTimestamp ) then
doSomething();
end
Code: Select all
doSomethingTimestamp = Timestamp:now():addSeconds(3);
...
if( doSomethingTimestamp:isPast() ) then
doSomething();
end
What other features do you think could be useful?