在 Perl 中,我如何找到上周四的日期?
在perl中,如何编写一个函数来获取上周四的日期?今天(11/21),我想要11/17。如何判断给定日期是否是星期日?
Possible Duplicate:
In Perl, how can find the date of the previous Monday for a given date?
In the perl, how to write a function to get last Thursday's date? Today (11/21), I want to get 11/17. How can I figure out if a given date is a Sunday or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
看起来像是 DateTime 的作品(通常推荐在 Perl 中操作日期的模块)。这个小例子应该可以回答您的两个问题:
Seems like a work for DateTime (which is the module usually recommended to manipulate dates in Perl). This small example should answer both your questions:
其他帖子也使用 DateTime,但它们存在本文所解决的问题。
解决的问题:
today
而不是now
,因为您只处理日期。注意:
更新:上述操作可能在某些日期、某些时区失败。 (并非所有日子都有午夜!)解决方案:
Other posts use DateTime too, but they have issues this post addresses.
Issues addressed:
today
instead ofnow
since you're only dealing with dates.Note:
Update: The above can fail on certain days for certain time zones. (Not all days have a midnight!) Solution:
我会使用拉森写的内容,尽管阅读 本地时间参考 不会伤害你。你可以这样做来检查是否是周日:
I'd use what larsen wrote, although reading the localtime reference won't hurt you. You could do something like this to check if its Sunday:
如果您想要测试的只是星期几,则 localtime() 的数组切片可以很好地工作:
If all you wanted to test was the day-of-the-week an array slice of the localtime() works nicely:
您还可以使用 Date::Calc:
You can also use Date::Calc:
仅使用
localtime
和POSIX
基础模块,您可以这样做:这将始终为您提供最后一个星期日之前的最后一个星期四。因此,如果当天是星期六,它将为您提供上一周的星期四,但如果当天是星期日,它将为您提供过去的最后一个星期四。
如果您更喜欢上周四的计算,您可以这样做:
With just
localtime
and thePOSIX
base module, you can do this:This will always give you the last Thursday before the last Sunday. So if the day is Saturday, it will give you the previous week's Thursday, but if it's Sunday, it will give you the last past Thursday.
If you prefer the last past Thursday computation, you might do this:
Date::Simple 有一个非常干净的界面。
Date::Simple has a pretty clean interface.