开发者

How to compare two strings based on date-time in perl & php?

I have strings in the (date-time) format- "Mon, 11 Jul 2011 11:45:07 +08:00", I need to compare such strings based on the date-time format, for finding most recent string. Which module/method shoul开发者_高级运维d i used here ?


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

my $time_str = 'Mon, 11 Jul 2011 11:45:07 +08:00';
# your notation of time zone
# does not comply with relevant standards
$time_str    =~ s/([+-]\d\d):(\d\d) \z/$1$2/msx; # kill colon

my $parser   = DateTime::Format::Strptime->new(
    pattern  => '%a, %d %b %Y %T %z',
    locale   => 'en',   # 'Mon', 'Jul' are English
    on_error => 'croak',
);

my $datetime = $parser->parse_datetime($time_str);

# Now you have a DateTime object. To compare,
# use the overloaded relation operators.
# <=> operator/sort function works as well.

if ($datetime < $a_different_datetime) {
    say 'earlier';
}


I use Date::Manip in Perl for this:

use Date::Manip;

my $datestr1 = "Mon, 11 Jul 2011 11:45:07 +08:00";
my $datestr2 = "Mon, 18 Jul 2011 11:45:07 +08:00";

my $date1 = new Date::Manip::Date;
my $date2 = $date1->new_date;
$date1->parse($datestr1);
$date2->parse($datestr2);

my $result = $date1->cmp($date2); # => -1, 0, 1

print $result, "\n";


For PHP, the easiest way would be converting the time strings with strtotime() and comparing the integer values. Highest integer is the latest.

Note that some versions of PHP will warn you when using Date functions if you have not set your default timezone. You can do so with date_default_timezone_set("") or php.ini's date.timezone = "", with the list of supported timezones.


In PHP it's called strtotime()


you can try strtotime() on the timestamp you have. then just compare the numbers using normal comparators.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜