-1

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

例如,假设今天是 2013 年 1 月 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";

谢谢 !!

4

2 回答 2

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);
}
于 2013-01-21T13:19:38.623 回答
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
于 2013-01-20T18:08:56.383 回答