Perl date calculation with dates format 2012-02-03 00:00:00
See DateTime .
#!/usr/bin/env perl
use strict; use warnings;
use DateTime;
my $ts = '2012-02-03 00:00:00';
my ($y, $m, $d) = ($ts =~ /([0-9]{4})-([0-9]{2})-([0-9]{2})/);
my $dt = DateTime->new(year => $y, month => $m, day => $d);
$dt->add( months => 2, days => 3 );
print $dt->strftime('%Y-%m-%d %H:%M:%S'), "\n";
It's actually a little cleaner to use the DateTime :: Format class and you get free error checking.
use DateTime::Format::Strptime qw( );
my $format = DateTime::Format::Strptime->new(
pattern => '%Y-%m-%d %H:%M:%S',
time_zone => 'local',
on_error => 'croak',
);
my $ts = '2012-02-03 00:00:00';
my $dt = $format->parse_datetime($ts);
$dt->add( months => 2, days => 3 );
print $format->format_datetime($dt), "\n";
source to share
The module Time::Piece
is a standard part of your Perl installation and will probably do whatever you need to do.
This program uses your approximate date and adds two months and three days, and then another 400 days. Two alternative ways of displaying values are displayed.
use strict;
use warnings;
use Time::Piece;
use Time::Seconds 'ONE_DAY';
my $format = '%Y-%m-%d %H:%M:%S';
my $dt = Time::Piece->strptime('2012-02-03 00:00:00', $format);
$dt = $dt->add_months(2);
$dt += 3 * ONE_DAY;
print $dt->strftime($format), "\n";
$dt += 400 * ONE_DAY;
printf "%s %s\n", $dt->ymd, $dt->hms;
Output
2012-04-06 00:00:00
2013-05-11 00:00:00
source to share
This is quite possible in the kernel using timing functions POSIX
.
The standard function POSIX::mktime
already deals with denormalized values and can fix in days / months out of range. Also, POSIX::strftime
it actually calls this on the given values before formatting them, so it will tune properly.
use POSIX qw( strftime mktime );
use POSIX::strptime qw( strptime );
my $format = "%Y-%m-%d %H:%M:%S";
my @t = strptime( "2012-02-03 00:00:00", $format );
@t = @t[0..5]; # Throw away wday and yday
$t[3] += 3; # mday
$t[4] += 2; # mon
say strftime $format, @t;
$t[3] += 400; # mday
say strftime $format, @t;
gives
2012-04-06 00:00:00
2013-05-11 00:00:00
source to share