簡體   English   中英

將舊的Unix日期轉換為Perl並進行比較

[英]Convert Old Unix Date to Perl and compare

要求 - 我的文件名稱為“Rajesh.1202242219”。 數字只不過是日期“ date '+%y''%m''%d''%H''%M' “格式。 現在我正在嘗試編寫一個perl腳本來從文件名中提取數字並與當前系統日期和時間進行比較,並根據此比較的輸出,使用perl打印一些值。

做法:

從文件名中提取數字:

if ($file =~ /Rajesh.(\d+).*/) {
print $1;
        }

將此時間轉換為perl中的可讀時間

my $sec  =  0;  # Not Feeded
my $min  =  19;
my $hour =  22;
my $day  =  24;
my $mon  = 02   - 1;
my $year = 2012 - 1900;
my $wday = 0;   # Not Feeded
my $yday = 0;   # Not Feeded

my $unixtime = mktime ($sec, $min, $hour, $day, $mon, $year, $wday, $yday);
print "$unixtime\n";
my $readable_time = localtime($unixtime);
print "$readable_time\n";

查找當前時間並比較...

my $CurrentTime = time();
my $Todaydate = localtime($startTime);

但問題是,我沒有得到如何從$1提取2位數並分配到$sec$min等的解決方案。任何幫助?

此外,如果您對此問題聲明有好的方法,請與我分享

我喜歡使用時間對象來簡化邏輯。 我在這里使用Time :: Piece因為它簡單而且重量輕(並且是核心的一部分)。 DateTime可以是另一種選擇。

use Time::Piece;
my ( $datetime ) = $file =~ /(\d+)/;
my $t1 = Time::Piece->strptime( $datetime, '%y%m%d%H%M' );
my $t2 = localtime(); # equivalent to Time::Piece->new

# you can do date comparisons on the object
if ($t1 < $t2) {
    # do something
    print "[$t1] < [$t2]\n";
}

不妨教DateTime :: Format :: Strptime使比較更加簡單:

use DateTime qw();
use DateTime::Format::Strptime qw();

if (
    DateTime::Format::Strptime
        ->new(pattern => '%y%m%d%H%M')
        ->parse_datetime('Rajesh.1202242219')
    < DateTime->now
) {
    say 'filename timestamp is earlier than now';
} else {
    say 'filename timestamp is later than now';
};
my ($year, $month, $day, $hour, $min) = $file =~ /(\d{2})/g;

if ($min) {
    $year += 100; # Assuming 2012 and not 1912
    $month--;
    # Do stuff
}

我認為unpack可能更合適。

if ( my ( $num ) = $file =~ /Rajesh.(\d+).*/ ) {
    my ( $year, $mon, $day, $hour, $min ) = unpack( 'A2 A2 A2 A2 A2', $num ); 
    my $ts = POSIX::mktime( 0, $min, $hour, $day, $mon - 1, $year + 100 );
    ...
}

使用分析日期的模塊可能會很好。 此代碼將解析日期並返回DateTime對象。 請參閱文檔以了解操作此對象的許多方法。

use DateTime::Format::Strptime;

my $date = "1202242219";
my $dt = get_obj($date);

sub get_obj {
    my $date = shift;
    my $strp = DateTime::Format::Strptime->new(
        pattern     => '%y%m%d%H%M'
    );
    return $strp->parse_datetime($date);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM