How can I get this week's dates in Perl?

后端 未结 4 1754
感情败类
感情败类 2021-02-09 04:44

I have the following loop to calculate the dates of the current week and print them out. It works, but I am swimming in the amount of date/time possibilities in Perl and want t

相关标签:
4条回答
  • 2021-02-09 04:52

    You can use the DateTime object to get the current day of the week as a number ( 1-7 ). Then just use that to find the current week's Monday. For example:

    my $today = DateTime->now;
    my $start = $today->clone;
    
    # move $start to Monday
    $start->subtract( days => ( $today->wday - 1 ) );   # Monday gives 1, so on monday we
                                                        # subtract zero. 
    
    my $end = $start->clone->add( days => 7 );
    

    The above is untested but the idea should work.

    0 讨论(0)
  • 2021-02-09 05:03

    Would this work:

    use strict;
    use warnings;
    use POSIX qw<strftime>;
    my ( $day, $pmon, $pyear, $wday ) = ( localtime )[3..6];
    $day -= $wday - 1; # Get monday
    for my $d ( map { $day + $_ } 0..6 ) { 
        print strftime( '%A, %B %d, %Y', ( 0 ) x 3, $d, $pmon, $pyear ), "\n";
    }
    

    I'm printing them only as an illustration. You could store them as timestamps, like this:

    use POSIX qw<mktime>;
    my @week = map { mktime(( 0 ) x 3, $day + $_, $pmon, $pyear ) } 0..6;
    
    0 讨论(0)
  • 2021-02-09 05:06

    A slightly improved version of friedo's answer ...

    my $start_of_week =
        DateTime->today()
                ->truncate( to => 'week' );
    
    for ( 0..6 ) {
        print $start_of_week->clone()->add( days => $_ );
    }
    

    However, this assumes that Monday is the first day of the week. For Sunday, start with ...

    my $start_of_week =
        DateTime->today()
                ->truncate( to => 'week' )
                ->subtract( days => 1 );
    

    Either way, it's better to use the truncate method than re-implement it, as friedo did ;)

    0 讨论(0)
  • 2021-02-09 05:06

    This should work:

    use POSIX; # for strftime
    my $time = time ();
    my $seconds = 24*60*60;
    my @time = gmtime ();
    $time = $time - $time[6] * $seconds;
    for my $wday (0..6) {
        $time += $seconds;
        my @wday = gmtime ($time);
        print strftime ("%A %d %B %Y\n", @wday);
    }
    

    Gives me:

    $ ./week.pl 
    Monday 24 May 2010
    Tuesday 25 May 2010
    Wednesday 26 May 2010
    Thursday 27 May 2010
    Friday 28 May 2010
    Saturday 29 May 2010
    Sunday 30 May 2010
    

    If you want to get weeks starting on Sunday, change $time[6] to ($time[6] + 1).

    This assumes you want the GMT weeks. Change gmtime to localtime to get local time zone weeks.

    0 讨论(0)
提交回复
热议问题