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

后端 未结 4 1791
感情败类
感情败类 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 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 ;)

提交回复
热议问题