#!/usr/bin/perl #--------------------------------------------------------------------- # format_date.pl # # format variable date inputs #--------------------------------------------------------------------- use strict; use warnings; use Date::Parse; use DateTime; my $DEFAULT_TIME_ZONE = "GMT"; my @dates = ( "0618-01-01 00:00:00", "1066-10-14 00:00:00", "1899-06-24 09:44:00", "1900-12-31 23:59:59", "1901-01-01 00:00:00", "1960-12-31 23:59:59", "1966-06-24 09:44:00", "1968-12-31 23:59:59", "1969-01-01 00:00:00", "1969-12-31 23:59:59", "1970-01-01 00:00:01", "2000-01-01 00:00:00", "2017-06-24 23:59:59", "2018-06-24 09:44:00", "2238-06-24 09:44:00" ); # define format for printf statements my $pstr = "%-19s %02s,%02s,%02s,%02s,%02s,%04s,%01s %-19s\n"; my $pfrm = "%19s %02u,%02u,%02u,%02u,%02u,%04u,%01u %19s\n"; printf( $pstr, "value", "ss", "mm", "hh", "dy", "mo", "year", "z", "date" ); foreach my $string (@dates) { # format datetime field from any valid datetime input # default time zone is used if timezone is not included in string my @datetime = strptime( $string, $DEFAULT_TIME_ZONE ); # error if date is not correctly parsed if ( scalar @datetime == 0 ) { die( "ERROR ====> invalid datetime ($string), " . "datetime format should be YYYY-MM-DD HH:MM:SS" ); } my ( $ss, $mm, $hh, $day, $month, $year, $zone ) = @datetime; if ( $year < 1000 ) { $year += 1900; } my %datetimehash = ( year => $year, month => $month + 1, day => $day, hour => $hh, minute => $mm, second => $ss, nanosecond => 0, time_zone => $zone, ); my $date = DateTime->new(%datetimehash); printf( $pfrm, $string, $ss, $mm, $hh, $day, $month, $year, $zone, $date ); } exit 0;