如何使用perl比较日期? [英] How to compare dates using perl?

查看:196
本文介绍了如何使用perl比较日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Perl 比较格式中的两个日期:

"dd mon yyyy hh:mm:ss GMT"

<块引用>

例如:2013 年 5 月 12 日 10:10:20 GMT

我无法安装任何外部 Perl 模块.请指教.

解决方案

如果你有 Perl v5.9.5 或更新版本,你可以使用 Time::Piece 核心模块.下面简单演示一下相关操作

  • 将日期从字符串转换为Time::Piece 对象

    my $date = "12 May 2013 10:10:20 GMT";我的 $tp1 = Time::Piece->strptime($date, "%d %B %Y %T %Z");我的 $tp2 = ...

  • 求2次的差

    我的 $diff = $tp2 - $tp1;

    它给你一个 Time::Seconds 对象.

  • 最后,以秒(或其他东西)为单位显示差异.

    print $diff->seconds;

  • 或者您可以直接比较两者(感谢 stevenl)

    $tp2 >$tp1

<小时>

参考文献:

  1. 时间::秒
  2. Time::Piece
  3. man strftime 用于与 Time::Piece 一起使用的格式字符串->strptime
  4. man strptime 用于与 $tp-> 一起使用的格式字符串;strftime
    • 请注意,如果您使用的是非 Unix 系统,则只有格式字符 aAbBcdHIjmMpSUwWxXyYZ% 是安全的(例如,Window 的 Perl 不支持 %e 说明符).

How can i compare two dates in the format using Perl:

"dd mon yyyy hh:mm:ss GMT"

e.g.: 12 May 2013 10:10:20 GMT

I cannot install any external Perl modules. Please advice.

解决方案

If you have Perl v5.9.5 or newer, you can use Time::Piece core module. Here's a simple demonstration of relevant operations

  • Convert the dates from string to Time::Piece object

    my $date = "12 May 2013 10:10:20 GMT";
    my $tp1 = Time::Piece->strptime($date, "%d %B %Y %T %Z");
    my $tp2 = ...
    

  • Find the difference between the 2 time

    my $diff = $tp2 - $tp1;
    

    which gives you a Time::Seconds object.

  • Finally, display the difference in units of seconds (or something else).

    print $diff->seconds;
    

  • Or you could just compare the two directly (thanks stevenl)

    $tp2 > $tp1
    


References:

  1. Time::Seconds
  2. Time::Piece
  3. man strftime for format string to use with Time::Piece->strptime
  4. man strptime for format string to use with $tp->strftime
    • Note that only format characters aAbBcdHIjmMpSUwWxXyYZ% are safe if you're using non-Unix system (for example, Window's Perl doesn't support the %e specifier).

这篇关于如何使用perl比较日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆