2014-12-23 20 views
-1

我認爲這是一個非常基本的問題。 但我嘗試過各種方法,無法弄清楚這一點。Perl在數據庫中定義爲字符串的比較日期

我有一個字符串值「21-01-2014」。我必須檢查這個日期是否大於2014年9月1日。

我該怎麼做?

我用解析日期。例如,

if (ParseDate($row->{Date}) >= ParseDate("01-09-2014")){ 
} 

但是這並沒有奏效。 可能在這裏有一個錯誤?

有人可以建議一個更簡單和直接的方法。 $ row->日期來自數據庫並被定義爲varchar。

謝謝。

+0

你從哪裏得到函數'ParseDate'?它是在第三方模塊中還是在您自己的代碼中定義的? – ThisSuitIsBlackNot

+0

假設我們正在討論[Time :: ParseDate](http://search.cpan.org/~muir/Time-modules-2003.0211/lib/Time/ParseDate.pm),我會注意到它解析日期作爲DD/MM/YYYY **「僅限於英國,或者無效的mm/dd/yyyy」**。美國式可能是1月9日的第二次日期。 –

+2

2014年1月的第二十一天在同年9月的第一天。所以你的'如果'條件_應該失敗。 –

回答

2

ParseDate從哪裏來?是Time::ParseDate?我想要Time::Piece。它已自5.10標準的Perl模塊,我可以指定日期是在另外的格式,Time::Piece是面向對象:

use strict;    # Lets you know when you misspell variable names 
use warnings;   # Warns of issues (using undefined variables 
use feature qw(say); 

use Time::Piece; 

my $time1 = "21-01-2014"; 
my $time2 = "01-09-2014"; #Assuming this is Sept, 1, 2014 

my $time_obj1 = Time::Piece->strptime("$time1", "%d-%m-%Y"); 
my $time_obj2 = Time::Piece->strptime("$time2", "%d-%m-%Y"); 

if ($time_obj1 < $time_obj2) { # Comparing number of days since "the epoc" 
    say $time_obj1->dmy . " is older than " . $time_obj2->dmy; 
} 
else { 
    say $time_obj2->dmy . " is older than " . $time_obj1->dmy; 
} 

如果您不希望創建對象,你可以簡單地使用由Time::Piece->strptime返回值:

if (Time::Piece->strptime("$time1", "%d-%m-%Y") 
     < Time::Piece->strptime("$time2", "%d-%m-%Y")) { 
    say "$time1 is older than $time2"; 
} 
else { 
    say "$time2 is older than $time1"; 
} 

字符串%d-%m-%Y是你日期的格式。 (你應該檢查返回值Time::Piece->strptime以確保你有一個有效的Time::Piece對象返回。爲簡單起見,我沒有這樣做)。

您可以在date的聯機幫助頁或strftime的聯機幫助頁上找到百分比格式代碼

+0

W,它按預期工作。我認爲這是最好也是最簡單的方法。 – Mahesh