我怎样才能在Perl中获得本周的日期?

前端之家收集整理的这篇文章主要介绍了我怎样才能在Perl中获得本周的日期?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下循环来计算当前周的日期并打印出来.它有效,但我在Perl的日期/时间可能性游泳,想要了解是否有更好的方法.这是我写的代码
  1. #!/usr/bin/env perl
  2. use warnings;
  3. use strict;
  4.  
  5. use DateTime;
  6.  
  7. # Calculate numeric value of today and the
  8. # target day (Monday = 1,Sunday = 7); the
  9. # target,in this case,is Monday,since that's
  10. # when I want the week to start
  11. my $today_dt = DateTime->now;
  12. my $today = $today_dt->day_of_week;
  13. my $target = 1;
  14.  
  15. # Create DateTime copies to act as the "bookends"
  16. # for the date range
  17. my ($start,$end) = ($today_dt->clone(),$today_dt->clone());
  18.  
  19. if ($today == $target)
  20. {
  21. # If today is the target,"start" is already set;
  22. # we simply need to set the end date
  23. $end->add( days => 6 );
  24. }
  25. else
  26. {
  27. # Otherwise,we calculate the Monday preceeding today
  28. # and the Sunday following today
  29. my $delta = ($target - $today + 7) % 7;
  30. $start->add( days => $delta - 7 );
  31. $end->add( days => $delta - 1 );
  32. }
  33.  
  34. # I clone the DateTime object again because,for some reason,# I'm wary of using $start directly...
  35. my $cur_date = $start->clone();
  36.  
  37. while ($cur_date <= $end)
  38. {
  39. my $date_ymd = $cur_date->ymd;
  40. print "$date_ymd\n";
  41. $cur_date->add( days => 1 );
  42. }

如上所述,这是有效的,但它是最快还是最有效的?我猜测速度和效率可能不一定在一起,但您的反馈非常感谢.

解决方法

friedo的答案略有改进……
  1. my $start_of_week =
  2. DateTime->today()
  3. ->truncate( to => 'week' );
  4.  
  5. for ( 0..6 ) {
  6. print $start_of_week->clone()->add( days => $_ );
  7. }

但是,这假设星期一是一周的第一天.星期天,从…开始

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

无论哪种方式,最好使用truncate方法而不是重新实现它,就像friedo所做的那样;)

猜你在找的Perl相关文章