如何在perl中比较字符串日期时间?
我的日期时间格式为字符串“11:56:41, 11/22/2011”。
这就是我想要的:
比较两个日期时间字符串。
$date1 = "11:56:41, 11/22/2011";
$date2 = "11:20:41, 11/20/2011";
if($date2 < $date1) {
do something...
} else {
do nothing...
}
我有什么想法如何在 Perl 中实现这一点吗?
I have this date time format in string "11:56:41, 11/22/2011".
Here's what I want:
Compare two date time strings like.
$date1 = "11:56:41, 11/22/2011";
$date2 = "11:20:41, 11/20/2011";
if($date2 < $date1) {
do something...
} else {
do nothing...
}
Any ideas how could i achieve this in perl?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
另一种解决方案是在将时间转换为 Time::Piece 对象后使用重载比较。对于一些简单的事情来说,创建这些对象可能有点大材小用,但如果您需要随时间做其他事情,它们就会变得非常有用。
One more solution that uses the overloaded comparisons after converting the times to
Time::Piece
objects. Creating the objects may be overkill for something simple, but they can become very useful if you need to do other things with the times.一种有效的方法是将字段重新排序为词汇上可比较的内容。
An efficient method is to reorder the fields to something lexically comparable.
什么,已经 4 个小时了,还没有一个 DateTime(所有人都欢呼强大的 DateTime)答案就在眼前?你偷懒了,perl 订阅者… ☻
方法
parse_datetime
返回DateTime
的实例其比较运算符和字符串化被重载到 DTRT。What, already 4 hours and not a single DateTime (all hail the mighty DateTime) answer in sight? You're slacking, perl subscribers… ☻
The method
parse_datetime
returns instances ofDateTime
whose comparison operators and stringification are overloaded to DTRT.将日期时间(在您的情况下,这些是本地日期时间,因为它们没有时区)转换为 ISO8601,然后您可以进行常规字符串比较。
要执行转换,您应该从格式中提取六个组件
并将它们重新组合成 ISO 8601:
然后就可以进行正常的词典比较了。
请参阅 http://codepad.org/berle9um
此处重复:
ADDENDUM
Convert the datetimes (in your case these are local datetimes because they have no time zones) into ISO8601 then you can do regular string comparison.
To perform the conversion, you should extract the six components from your format
and reassemble them into ISO 8601:
Then a normal lexicographic comparison will work.
See http://codepad.org/berle9um
Repeated here:
ADDENDUM
我用unixtime。 :)
我将两个时间都转换为 unixtime,然后我只有两个整数要比较,因此我可以使用运算符 <、==、>等
例如转换为unixtime如下
I use unixtime. :)
I convert both times to unixtime and then I just have two integers to compare and so I can use the operators <, ==, > etc
e.g. convert to unixtime as follows
在这种情况下,我一直使用
Date::Calc
:In this instance I've always used
Date::Calc
: