2013-01-20 31 views
-1

我想在perl腳本顯示過去3個月週日在Perl和ksh腳本

例如,顯示過去3個月週日,說今天是星期天二○一三年一月二十日,最近3個月週日從現在

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

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

應該改變基於當前日期和時間

最近3個月星期日需要的ksh腳本同樣的事情爲Linux

在此先感謝。


這裏是代碼..它是給最後sunday..But我需要近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"; 

謝謝!

+1

我們會很高興地幫助您解決您的編程問題,一旦您嘗試盡力並完全卡住,但Stack Overflow不是免費提供編程工作的站點。如果您顯示您的代碼並解釋問題,那麼我們將很樂意提供幫助。 – Borodin

+0

確定對不起,先生... – user1990571

+0

你似乎做了很難的部分。只需在幾秒鐘內減去七天,並且您會像以前一樣獲得前幾個星期日。 – Borodin

回答

0

在ksh的(與pdksh程序和GNU的coreutils日期測試):

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

使用Perl的日期時間模塊的簡單解決方案。

#!/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); 
}