以perl和ksh脚本显示最后3个月的星期日

时间:2013-01-20 07:09:01

标签: perl ksh

我希望在perl脚本中显示最近3个月的星期日

例如,今天说是星期日2013-01-20,从现在起的最后3个月

  2013-01-20
  .
  .
  2013-01-06
  .
  .
  2012-12-30

  2012-12-02
  .
  .
  2012-11-25
  .
  .
  2012-11-04

应根据当前日期和时间更改过去3个月的星期日

在Linux的ksh脚本中需要相同的东西

提前致谢。


这是代码..它是给最后一个星期天..但我需要最后3个月的星期日

#!/usr/bin/perl

$today = date(time);
$weekend = date2(time);

sub date {
     my($time) = @_;     

     @when = localtime($time);
     $dow=$when[6];
     $when[5]+=1900;
     $when[4]++;
     $date = $when[5] . "-" . $when[4] . "-" . $when[3];

     return $date;
}


sub date2 {
     my($time) = @_;     # incoming parameters

     $offset = 0;
     $offset = 60*60*24*$dow;
     @when = localtime($time - $offset);
     $when[5]+=1900;
     $when[4]++;
     $date = $when[5] . "-" . $when[4] . "-" . $when[3];

     return $date;
}


print "$weekend \n";

谢谢!

2 个答案:

答案 0 :(得分:0)

在ksh中(使用pdksh和GNU coreutils日期测试):

timestamp=`date +%s`
date=`date --date=@$timestamp +%F`
month=`date --date=@$timestamp +%Y-%m`
for months in 1 2 3; do
    while [[ $month == `date --date=@$timestamp +%Y-%m` ]]
    do
        if [[ 7 == `date --date=@$timestamp +%u` ]]; then echo $date; fi
        let timestamp-=12*60*60
        date=`date --date=@$timestamp +%F`
    done
    month=`date --date=@$timestamp +%Y-%m`
done | uniq

答案 1 :(得分:0)

使用Perl的DateTime模块的简单解决方案。

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use DateTime;

# Get the current date and time
my $now = DateTime->now;

# Work out the previous Sunday
while ($now->day_of_week != 7) {
  $now->subtract(days => 1);
}

# Go back 13 weeks from the previous Sunday
my $then = $now->clone;
$then->subtract(weeks => 13);

# Decrement $now by a week at a time until
# you reach $then
while ($now >= $then) {
  say $now->ymd;
  $now->subtract(weeks => 1);
}