Hi thimes,
It depends a bit on what kind of math you want to do and whether you want leap seconds (pointed out by anita2R, thanks) to be considered. Personally, unless high performance must be considered, I like to throw all of my math at the DateTime module. The following shows the different ways you can do the math:
#!/usr/bin/env perl
use warnings;
use strict;
use DateTime;
my $dt_customepoch = DateTime->new(
year=>2000, month=>1, day=>1,
hour=>12, minute=>0, second=>0,
time_zone=>'UTC' );
print "dt_customepoch: ",
$dt_customepoch->strftime('%b %e %Y, %T %Z'), "\n";
my $s_customepoch = $dt_customepoch->epoch;
print " s_customepoch: $s_customepoch\n";
### Obtaining DateTime object from a value expressed in
# seconds since the custom epoch (let's call it "sce")
my $sce_one = 128072700; # Thu Jan 22 19:45:00 2004
print " sce_one: $sce_one\n";
my $dt_one = DateTime->from_epoch(
# Note the addition here
epoch => $s_customepoch + $sce_one,
# from_epoch defaults to UTC, but we'll be explicit
time_zone=>'UTC' );
print " dt_one: ", $dt_one->strftime('%b %e %Y, %T %Z'),
" (epoch=", $dt_one->epoch, ")\n";
#### Doing math in the "seconds since custom epoch" domain
# Add 3 years, 21 days*, -4 hours, 11 minutes
# * adjusted +1 for 2004 being leap year
my $s_offset = 60*60*24*365*3 + 60*60*24*(21+1)
- 60*60*4 + 60*11;
print " s_offset: $s_offset\n";
my $sce_two = $sce_one + $s_offset;
print " sce_two: $sce_two\n";
my $dt_two = DateTime->from_epoch( time_zone=>'UTC',
epoch => $s_customepoch + $sce_two );
print " dt_two: ", $dt_two->strftime('%b %e %Y, %T %Z'),
" (epoch=", $dt_two->epoch, ")\n";
### Doing the same math in the DateTime domain
my $dt_three = $dt_one->clone->add(
# Note how no adjustment for the leap year is needed
years=>3, days=>21, hours=>-4, minutes=>11);
print " dt_three: ", $dt_three->strftime('%b %e %Y, %T %Z'),
" (epoch=", $dt_three->epoch, ")\n";
#### Obtaining "seconds from custom epoch"
# using regular subtraction vs. DateTime math
my $sce_threea = $dt_three->epoch - $s_customepoch;
print "sce_threea: $sce_threea\n";
my $sce_threeb = $dt_three
->subtract_datetime_absolute($dt_customepoch)
->in_units('seconds');
# Leap second (Dec 31, 2005 23:59:60 UTC) is considered!
print "sce_threeb: $sce_threeb\n";
__END__
dt_customepoch: Jan 1 2000, 12:00:00 UTC
s_customepoch: 946728000
sce_one: 128072700
dt_one: Jan 22 2004, 19:45:00 UTC (epoch=1074800700)
s_offset: 96495060
sce_two: 224567760
dt_two: Feb 12 2007, 15:56:00 UTC (epoch=1171295760)
dt_three: Feb 12 2007, 15:56:00 UTC (epoch=1171295760)
sce_threea: 224567760
sce_threeb: 224567761
Hope this helps, -- Hauke D |