本文介绍了Perl - 如何从给定的日期获取上一个星期三的日期,而不使用DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
全部,
我想从给定的日期找出上个星期三的日期。
I want to find out the date of previous wednesday from the given date.
例如。我有日期为20150804,我需要20150729。
Eg. I have date as "20150804" and i would need "20150729".
DateTime不可用,我也无法安装。
DateTime is not available and i cannot install it as well.
我看了几个例子,但是他们使用的是DateTime。
I looked at few examples but they were using DateTime.
你可以重定向我可以得到一些帮助吗?谢谢。
Can you please redirect me where i can get some help.? Thanks.
我打算在下面编写代码。
I am planning to code something like below.
代码:
#!/opt/perl-5.8.0/bin/perl
use warnings;
use strict;
my $dt="20150804";
my $prevWednesday=getPrevWednesday($dt);
sub getPrevWednesday()
{
my $givenDt=shift;
...
}
推荐答案
另一个强力的方法,这次使用另一个核心模块。
Another brute force approach, this time using another core module Time::Local.
#!/usr/bin/perl
use warnings;
use strict;
use Time::Local;
sub prev_wednesday {
my $date = shift;
my ($year, $month, $day) = $date =~ /(....)(..)(..)/;
my $time = timelocal(0, 0, 12, $day, $month - 1, $year);
do { $time -= 60 * 60 * 24 } until (localtime $time)[6] == 3; # <- Wednesday
my ($y, $m, $d) = (localtime $time)[5, 4, 3];
return sprintf "%4d%02d%02d\n", 1900 + $y, $m + 1, $d;
}
print $_, ' ', prev_wednesday($_), for qw( 20150804 20150805 20150806
20150101 20000301 20010301 );
这篇关于Perl - 如何从给定的日期获取上一个星期三的日期,而不使用DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!