NAME
DateTime::Precise - Perform common time and date operations with additional GPS operations
SYNOPSIS
use DateTime::Precise;
use DateTime::Precise qw(:TimeVars);
# Constructors and ways to set time.
$t1 = DateTime::Precise->new;
$t2 = DateTime::Precise->new('1998. 4. 3 12:13:44.054');
$t3 = DateTime::Precise->new(time() - 100.23456);
$t4 = DateTime::Precise->new('1998.04.24');
$t1->set_localtime_from_epoch_time;
$t1->set_gmtime_from_epoch_time(time + 120.987);
$t1->set_from_datetime('1998.03.23 16:58:14.65');
$t1->set_time('YDHMS', 1998, 177, 9, 15, 26.5);
# This is the same as $d3->set_from_datetime(...)
$t3->dscanf("%^Y.%M.%D %h:%m:%s", "1998.03.25 20:25:23");
if ($msg = $d1->dscanf("%~M", $input)) {
print "error: $msg\n";
print "Must enter a three-letter month abbrev.\n";
}
# Get different parts of the time.
$year = $t3->year;
$month = $t3->month;
$day = $t3->day;
$hours = $t3->hours;
$minutes = $t3->minutes;
$seconds = $t3->seconds;
($year, $day_of_year) = $t3->get_time('Yj');
# Print times and dates.
print $t2->asctime;
print $t2->strftime('%T %C%n');
print $t2->dprintf("%^Y.%M.%D %h:%m:%s"); # datetime
print $t2->dprintf("%~w %~M %-D %h:%m:%s CST %^Y"); # ctime
# Copy times.
my $t4 = $t2->copy;
# Set one time object to the same time as another: set $t3 equal to $t2.
$t3->clone($t2);
# Find the difference between two times.
$secs_from_midnight = $t4 - $t1;
$secs_from_midnight = $t4->diff($t1);
# Add seconds, days, months, etc to time.
$t1 = $t4 + 3600; # $t1 is now an hour after midnight
$t1->inc_month(2); # add two months to $t1
$t1->floor_month; # set $t1 to the first of the month
$t1 -= 0.25; # subtract 1/4 of a second from $t1
# Can compare and sort DateTime::Precise.
print "It's late!!!" if ($t1 > $t4);
@sorted = sort @birthdays; # normal comparisons work fine
# Get the GPS weeks, seconds and day.
$gps_week = $t1->gps_week;
$gps_seconds = $t1->gps_seconds;
$gps_day = $t1->gps_day;
($gps_week, $gps_seconds, $gps_day) = $t1->gps_week_seconds_day;
DESCRIPTION
The purpose of this library was to replace our dependence on Unix epoch time, which, being limited to a range of about 1970 to 2030, is inadequate for our purposes (we have data as old as 1870). This date library effectively handles dates from A.D. 1000 to infinity, and would probably work all the way back to 0 (ignoring, of course, the switch-over to the Gregorian calendar). The useful features of Unix epoch time (ease of date difference calculation and date comparison, strict ordering) are preserved, and elements such as human-legibility are added. The library handles fractional seconds and some date/time manipulations used for the Global Positioning Satellite system.
The operators +/-, <=>, cmp, stringify are overloaded. Addition handles seconds and fractions of seconds, subtraction handles seconds or date differences, compares work, and stringification returns the a representation of the date.
The US Geological Survey (USGS) likes midnight to be 24:00:00 of the previous day, not 00:00:00 of the day people expect. If $DateTime::Precise::USGSMidnight is set, dprintf will always print midnight as 24:00:00 and the date returned from dprintf will have the previous day's date. Regardless, time is always stored internally as 00:00:00.
CONSTRUCTOR
- new
- new('1998. 4. 3 12:13:44')
- new(time() - 100.23456)
- new('YDHMS', 1998, 200, 13, 16, 49.5)
-
This creates a new time object. If no argument is passed, then the time object is initialized with the time returned from gmtime (time()). The second form is used to set the time explicitly. The argument can be in one of three formats: "YYYY.MM.DD hh:mm:ss.ffff", "YYYY.MM.DD" (midnight assumed), or "YYYYMMDDhhmmss.ffff". Here ffff are the fractions of seconds. The third form sets the time using gmtime() with fractional seconds allowed. The fourth form sets the time using a format as the first argument followed by the particular date adjustments as the following arguments. See set_time() for more information. If the new fails, then new returns an empty list in a list context, an undefined value in a scalar context, or nothing in a void context.
Because the second and third forms pass only one argument to new(), there must be a way of distinguishing them. Currently the following test is used: if any non-digit characters are found in the argument or if the string form of the argument is longer than 10 character, then assume it to be a string to parse for the date. Otherwise it is the time since the Unix epoch. The string length of 10 was chosen since when the Unix epoch time flips to 11 digits, it'll be roughly year 2287.
METHODS
- set_from_datetime datetime
-
Set date/time from passed date/time string "YYYY.MM.DD hh:mm:ss.fff". If set_from_datetime successfully parses datetime, then the newly set date/time object is returned, otherwise it returns an empty list in a list context, an undefined value in a scalar context, or nothing in a void context.
- set_localtime_from_epoch_time [epoch]
-
Set from epoch time into the local time zone. If epoch is passed, then use that time to set the current time, otherwise use the time as returned from time() or from Time::HiRes::time() if the Time::HiRes module can be loaded. If the Time::HiRes::time() can be imported, then the resulting loaded time most likely will contain a fractional second component. The newly set date/time object is returned. The epoch can contain fractional seconds.
- set_gmtime_from_epoch_time [epoch]
-
Set from the epoch time into the standard Greenwich time zone. If epoch is passed, then use that time to set the current time, otherwise use the time as returned from time() or from Time::HiRes::time() if the Time::HiRes module can be loaded. If the Time::HiRes::time() can be imported, then the resulting loaded time most likely will contain a fractional second component. The newly set date/time object is returned. The epoch can contain fractional seconds.
- set_from_day_of_year year day_of_year
-
Set date/from from the year and the decimal day of the year. Midnight January 1st is day 1, noon January 1st is 1.5, etc. If the date was successfully set, then the newly set date/time object is returned, otherwise it returns an empty list in a list context, an undefined value in a scalar context, or nothing in a void context.
- set_from_serial_day serial_day_number
-
Set the date/time from the serial day. See also serial_day(). If the date was successfully set, then the newly set date/time object is returned, otherwise is returns an empty list in a list context, an undefined value in a scalar context, or nothing in a void context.
- set_from_gps_week_seconds gps_week gps_seconds
-
Set the current time using the number of weeks and seconds into the week since GPS epoch (January 6, 1980 UTC). If the date was successfully set, then the newly set date/time object is returned, otherwise is returns an empty list in a list context, an undefined value in a scalar context, or nothing in a void context.
- set_time format [arg, [arg, ...]]
-
Set the time. format is a string composed of a select set of characters. Some characters may take an optional argument, which are listed following the format argument in the same order as the characters. The first character must be an absolute time:
N => Set time to now. No argument taken. G => Set time to GPS time 0 (January 6, 1980). No argument taken. Y => Set time to beginning of the year. Argument taken. J => Set time to modified Julian date. Argument taken. s => Set time to seconds since January 1, 1970. Argument taken.
These characters represent modifiers to the time set using the above characters:
B => Add months to time. Argument taken. W => Add weeks to time. Argument taken. D => Add days counted from 1 to time. Argument taken. d => Add days counted from 0 to time. Argument taken. H => Add hours to time. Argument taken. M => Add minutes to time. Argument taken. S => Add seconds to time. Argument taken.
If the date and time was successfully set, then it returns the newly set date/time object, otherwise set_time() returns an empty list in a list context, an undefined value in a scalar context, or nothing in a void context and the date and time remain unchanged.
- get_time string
-
Return an array, where each element of the array corresponds to the corresponding strftime() value. This string should not contain % characters. This method is a much, much better and faster way of doing
map {$self->strftime("%$_")} split(//, $string)
- year [year]
-
Return the year. If an argument is passed to year, then set the year to the the integer part of the argument and then return the newly set year.
- month [month]
-
Return the numerical month (1 = January, 12 = December). If an argument is passed to month, then set the month to the integer part of the argument and return the newly set month.
- day [day]
-
Return the day of the month. If an argument is passed to day, then set the day to the integer part of the argument and return the newly set day.
- hours [hours]
-
Return the hours in the day. If an argument is passed to hours, then set the hours to the integer part of the argument and return the newly set hours.
- minutes [minutes]
-
Return the minutes in the hour. If an argument is passed to minutes, then set the minutes to the integer part of the argument and return the newly set minutes.
- seconds [seconds]
-
Return the seconds in the minutes. If an argument is passed to seconds, then set the seconds to the argument and return the newly set seconds. This argument accepts fractional seconds and will return the fractional seconds.
- serial_day
-
Returns a serial day number representing the date, plus a fraction representing the time since midnight (i.e., noon=0.5). This is for applications which need an scale index (we use it for positioning a date on a time-series graph axis). See also set_from_serial_day().
- day_of_year
-
Return the day of the year including the fraction part of the day. Midnight January 1st is day 1, noon January 1st is 1.5, etc.
- julian_day
-
Return the day of the year including the fraction part of the day where time is 0 based. Midnight January 1st is day 0, noon January 1st is 0.5, noon January 2nd is 1.5, etc.
- unix_seconds_since_epoch
-
Return the time in seconds between the object and January 1, 1970 UTC.
- gps_seconds_since_epoch
-
Return the time in seconds between the object and January 6, 1980 UTC.
- gps_week_seconds_day
-
Return an array consisting of the GPS week 0 filled to four spaces, the number of seconds into the GPS week, and the GPS day, where day 0 is Sunday.
- gps_week
-
Return the GPS week of the object. The returned number is 0 filled to four digits.
- gps_seconds
-
Return the number of seconds into the current GPS week for the current object.
- gps_day
-
Return the GPS day of the week for the current object, where day 0 is Sunday.
- copy
-
Return an identical copy of the current object.
- clone other_dt
-
Set this DateTime::Precise equal to other_dt.
- dprintf string
-
Returns string with substitutions:
%x number zero-padded to 2 digits (ie, '02') %C<-x> number space-padded to 2 digits (ie, ' 2') %^x unpadded number (ie, '2') %~x 3-letter abbrev corresponding to value (%M and %w only) %*x full name corresponding to value (%M and %w only) %% '%'
where x is one of:
h hours (0..23) m minutes (0..59) s seconds (0..59) D day of the month (1..31) M month (1..12) Y years since 1900 (ie, 96) W USGS water year (year+1 for months Oct-Dec) w day of the week (0..6, or "Mon", etc.) E internal string (no ~^*-)
so, for example, to get a string in datetime format, you would pass a string of '%^Y.%M.%D %h:%m:%s', or, to get a ctime-like string, you would pass:
'%~w %~M %-D %h:%m:%s CDT %^Y'
(presuming you're in the CDT. Maybe timezone support will show up some day).The US Geological Survey (USGS) likes midnight to be 24:00:00 of the previous day, not 00:00:00 of the day people expect. If $DateTime::Precise::USGSMidnight is set, dprintf will always print midnight as 24:00:00 and the date returned from dprintf will have the previous day's date. Regardless, time is always stored internally as 00:00:00.
- dscanf format string
-
Takes a format string format, and use it to read the date and time fields from the supplied string. The current date and time is unchanged if dscanf fails.
All format characters recognized by dprintf() are valid. Two additional characters are recognized, 'U' which sets the time to the local time/date using the number of seconds since Unix epoch time and 'u' which sets the time to GMT time/date using the number of seconds since Unix epoch time. Unless exact characters are supplied or format characters are concatenated, will separate on non-matching characters.
- strftime format
-
Just like the strftime() function call. This version is based on the Solaris manual page. format is a string containing of zero or more conversion specifications. A specification character consists of a '%' (percent) character followed by one conversion characters that determine the conversion specifications behavior. All ordinary characters are copied unchanged to the return string.
The following GPS specific conversions are supported in this strftime: %s the seconds since UTC January 1, 1970 %G the GPS week (4 digits with leading 0's) %g the GPS seconds into the GPS week with no leading zeros %f the GPS day where 0 = Sunday, 1 = Monday, etc %F the GPS day where 1 = Sunday, 2 = Monday, etc
The following standard conversions are understood:
%% the same as % %a the abbreviated weekday name %A the full weekday name %b the abbreviated month name %B the full month name %c the appropriate date and time representation %C century number (the year divided by 100 and truncated to an integer as a decimal number [1,99]); single digits are preceded by 0 %d day of month [1,31]; single digits are preceded by 0 %D date as %m/%d/%y %e day of month [1,31]; single digits are preceded by a space %h locale's abbreviated month name %H hour (24-hour clock) [0,23]; single digits are preceded by 0 %I hour (12-hour clock) [1,12]; single digits are preceded by 0 %j day number of year [1,366]; single digits are preceded by 0 %k hour (24-hour clock) [0,23]; single digits are preceded by a blank %l hour (12-hour clock) [1,12]; single digits are preceded by a blank %m month number [1,12]; single digits are preceded by 0 %M minute [00,59]; leading zero is permitted but not required %n insert a newline %p either AM or PM %r appropriate time representation in 12-hour clock format with %p %R time as %H:%M %S seconds [00,61] %t insert a tab %T time as %H:%M:%S %u weekday as a decimal number [1,7], with 1 representing Sunday %U week number of year as a decimal number [00,53], with Sunday as the first day of week 1 %V week number of the year as a decimal number [01,53], with Monday as the first day of the week. If the week containing 1 January has four or more days in the new year, then it is considered week 1; otherwise, it is week 53 of the previous year, and the next week is week 1. %w weekday as a decimal number [0,6], with 0 representing Sunday %W week number of year as a decimal number [00,53], with Monday as the first day of week 1 %x locale's appropriate date representation %X locale's appropriate time representation %y year within century [00,99] %Y year, including the century (for example 1993) %Z Always GMT
- asctime
-
Return a string such as 'Fri Apr 3 12:13:44 GMT 1998'. This is equivalent to strftime('%c').
Incrementing and rounding
There are many subroutines of the format 'func_unit', where func is one of (inc, dec, floor, ceil, round) and unit is one of (second, minute, hour, day, month, year) [second and minute can be abbreviated as sec and min respectively].
inc_unit(i) increments the date by i units (i defaults to 1 if no parameter is supplied). For days through seconds, fractional increments are allowed. However, for months and years, only the integer part of the increment is used.
dec_unit(i) identical to inc_unit(-i
).
round_unit() rounds the date to the nearest unit. Rounds years down for Jan-Jun, and up for Jul-Dec; months down for 1st-15th and up for 16th and later; days round up on or after 12:00:00; hours on or after xx:30:00, minutes on or after 30 seconds; seconds on or after 0.5 seconds.
floor_unit() rounds the date down to the earliest time for the current unit. For example, floor_month() rounds to midnight of the first day of the current month, floor_day() to midnight of the current day, and floor_hour() to xx:00:00.
ceil_unit() is the complementary function to floor. It rounds the date up, to the earliest time in the next unit. E.g., ceil_month() makes the date midnight of the first day of the next month.
Overloaded operators
Addition, subtraction, and comparison operators are overloaded, as well as the string representation of a date object.
# create a new object
$x = DateTime::Precise->new('1996.05.05 05:05:05');
# copy it
$y = $x;
# increment x by one second
$x++;
# decrement by a day
$y = $y - 86400;
# test em
print ($x < $y ? "x is earlier\n" : "y is earlier\n");
# get the difference
print "The difference between x and y is ", $x-$y, " seconds.\n";
If $x is a date object, $x + $i
is identical to $x->inc_sec($i).
There are two possible results from subtraction. $x - $i
, where $i is a number, will return a new date, $i seconds before $x. $x - $y
, where $y is another date object, is identical to $x->diff($y).
Comparison operators (<,>,==,etc) work as one would expect.
PUBLIC CONSTANTS
The following variables are not imported into your package by default. If you want to use them, then use
use DateTime::Precise qw(:TimeVars);
in your package. Otherwise, you can use the fully qualified package name, such as $DateTime::Precise::USGSMidnight.
- $USGSMidnight
-
Set this to 1 if you want midnight represented as 24:00:00 of the previous day. The default value is 0 which does not change the behavior of midnight. To use this variable in your code, load the DateTime::Precise module like this:
use DateTime::Precise qw($USGSMidnight);
Setting this only changes the output of dprintf for date and times that are exactly midnight.
- @MonthDays
-
Days per month in a non-leap year. This array is 1 indexed, so 0 is December, 1 is January, etc.
- @MonthName
-
Month names. This array is 1 indexed, so 0 is December, 1 is January, etc.
- @MonthAbbrev
-
Month abbreviated names. This array is 1indexed, so 0 is Dec, 1 is Jan, etc.
- @WeekName
-
Names of the week, 0 indexed. So 0 is Sunday, 1 is Monday, etc.
- @WeekAbbrev
-
Abbreviated names of the week, 0 indexed. So 0 is Sun, 1 is Mon, etc.
- &Secs_per_week
-
The number of seconds in one week (604800).
- &Secs_per_day
-
The number of seconds in one day (86400).
- &Secs_per_hour
-
The number of seconds in one hour (3600).
- &Secs_per_minute
-
The number of seconds in one minute (60).
- &JANUARY_1_1970
-
Subroutine returning the Unix epoch time January 1, 1970 UTC.
- &JANUARY_6_1980
-
Subroutine returning the GPS epoch time January 6, 1980 UTC.
PUBLIC SUBROUTINES
- IsLeapYear(year)
-
Returns true if the argument is a leap year.
- DaysInMonth(month, year)
-
Returns the number of days in the month.
IMPLEMENTATION
This package is based on the DateTime package written by Greg Fast <gdfast@usgs.gov>. The _week_of_year routine is based on the Date_WeekOfYear routine from the Date::DateManip package written by Sullivan Beck.
Instead of using the string representation used in the original DateTime package, this package represents the time internally as a seven element array, where the elements correspond to the year, month, day, hours, minutes, seconds, and fractional seconds.
AUTHOR
Contact: Blair Zajac <blair@orcaware.com>. The original version of this module was based on DateTime written by Greg Fast <gdfast@usgs.gov>.
5 POD Errors
The following errors were encountered while parsing the POD:
- Around line 2024:
=back doesn't take any parameters, but you said =back 4
- Around line 2330:
=back doesn't take any parameters, but you said =back 4
- Around line 2398:
'=item' outside of any '=over'
- Around line 2457:
You forgot a '=back' before '=head1'
- Around line 2469:
=back doesn't take any parameters, but you said =back 4