Time::Piece#
Date and time objects: use Time::Piece makes localtime and gmtime return an object with accessors for every field, formatting and parsing, comparison, and arithmetic with the durations of Time::Seconds. In string context the object is still the familiar scalar localtime text (Tue Nov 14 22:13:20 2023).
This is Time::Piece 1.41; Time/Piece.pm and Time/Seconds.pm are upstream’s. Formatting, parsing and the breaking down of an epoch run natively; parsing (strptime) does not depend on the system’s library, so a format parses the same way everywhere.
Synopsis#
use Time::Piece;
use Time::Seconds;
my $t = gmtime(1_700_000_000);
print $t->ymd, ' ', $t->hms, "\n"; # 2023-11-14 22:13:20
print $t->year, ' ', $t->mon, ' ', $t->monname, "\n"; # 2023 11 Nov
print $t->strftime('%A, %d %B %Y'), "\n"; # Tuesday, 14 November 2023
print $t->epoch, "\n"; # 1700000000
my $later = $t + ONE_DAY * 3;
print $later->ymd, "\n"; # 2023-11-17
print +($later - $t)->days, " days\n"; # 3 days
print $t->add_months(3)->ymd, "\n"; # 2024-02-14
my $p = Time::Piece->strptime('2024-02-29 12:00', '%Y-%m-%d %H:%M');
print $p->is_leap_year ? "leap\n" : "common\n"; # leap
print $p > $t ? "later\n" : "earlier\n"; # later
The interface#
Making one -
localtime($epoch),gmtime($epoch)(now without an argument),Time::Piece->strptime($string, $format), andTime::Piece->new($epoch).Fields -
sec,min,hour,mday(day_of_month),mon(1-12),_mon(0-11),monname/month,fullmonth,year,yy,wday(1 = Sunday),_wday(0 = Sunday),day_of_week,wdayname,fullday,yday(day_of_year),isdst,tzoffset,epoch,week(ISO 8601),julian_day,mjd,is_leap_year,month_last_day.Text -
ymd,mdy,dmy,hms(each with an optional separator),datetime(ISO 8601),cdate,strftime($format).Arithmetic -
+and-with seconds or aTime::Seconds(ONE_DAY,ONE_WEEK,ONE_HOUR, …); two objects subtract to aTime::Seconds(->days,->hours,->minutes);add_months,add_years;<,==,<=>andcmpcompare.Locale -
day_list,mon_listand theirfullforms set or read the namesstrftimeandstrptimeuse;Time::Piece::use_locale()takes them from the current locale.
Differences from upstream#
None: upstream’s tests pass unchanged (t/81-xs-native/Time-Piece, the upstream files), and 010-050 there check formatting, parsing and the field breakdown against perl 5.44.