比较两个不同格式的日期

比较两个不同格式的日期

我有两个文件,每个文件包含不同的日期格式,如下所示:

文件1:

2014-NOV-0620:59:59

文件2:

2014-12-31

如何在 awk 中比较这两个日期?

答案1

Perl 很方便

use Time::Piece;

my $date1 = "2014-NOV-0620:59:59";
my $date2 = "2014-12-31";

my $datetime1 = Time::Piece->strptime($date1, "%Y-%b-%d%H:%M:%S");
my $datetime2 = Time::Piece->strptime($date2, "%Y-%m-%d");

if ($datetime1 < $datetime2) {
    print "$date1 is earlier than $date2\n";
}
elsif ($datetime1 > $datetime2) {
    print "$date1 is later than $date2\n";
}
else {
    print "$date1 is equal to $date2\n";
}

GNU awk:

gawk '
    function parse_date_fmt_1(date,     epoch, regex, month) {
        regex = "([[:digit:]]{4})-([[:alpha:]]{3})-([[:digit:]]{2})([[:digit:]]{2}):([[:digit:]]{2}):([[:digit:]]{2})"
        if (match(date, regex, m)) {
            month = index("..JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC", toupper(m[2])) / 3
            epoch = mktime(m[1] " " month " " m[3] " " m[4] " " m[5] " " m[6])
        }
        return epoch
    }

    function parse_date_fmt_2(date,     epoch, regex) {
        regex = "([[:digit:]]{4})-([[:digit:]]{2})-([[:digit:]]{2})"
        if (match(date, regex, m)) {
            epoch = mktime(m[1] " " m[2] " " m[3] " 0 0 0")
        }
        return epoch
    }

    BEGIN { 
        date1 = "2014-NOV-0620:59:59"
        print parse_date_fmt_1(date1)

        date2 = "2014-12-31"
        print parse_date_fmt_2(date2)
    }
'

答案2

指定特定日期/时间仅与日期进行比较是有问题的。指定日期的时间是什么?我将假设一天中的第一时刻(午夜)。总体思路是生成自 UNIX 纪元以来的秒数,因此比较它们很简单。

d2=$( date -d "2014-12-31" "+%s" )
echo $d2
1420009200

#date cmd requires day-month-year order (if month is alpha) and proper case
fixed_date=$( echo $a | awk '{a=substr($0,0,11);b=substr($0,12,19);printf("%11s %8s\n",a,b)}' | awk '{a=tolower($0);print a}' | sed 's/[[:alpha:]]/\u&/' | awk 'BEGIN{FS="[- ]"};{print $3"-"$2"-"$1,$4}' )

d1=$( date -d "$fixed_date" "+%s" )
echo $d1
1415332799

#compare to confirm the time between dates
echo "($d2-$d1)/60/60/24" | bc -l
54.125...

#example - convert seconds back to a date
date -d @$d2 +"%Y-%m-%d %H:%M:%S"
2014-12-31 00:00:00

相关内容