【问题标题】:How to get this day last year in PHP?如何在 PHP 中获得去年的这一天?
【发布时间】:2015-07-15 13:05:37
【问题描述】:

所以我目前正在使用 Carbon 来获取日期、时间和比较。我可以轻松地完成 subYear() 来获得去年的 date。现在我需要一些东西才能在去年的同一时间获得完全相同的 day,例如 4 月第二周的星期三。

我希望必须做一些事情来解决一周中的当前日期,例如 3 和一年中的当前周,然后在去年得到相同的值。

只是想我会检查是否有任何可用的东西已经在 Carbon 或其他 PHP 工具中执行此操作?谢谢

【问题讨论】:

  • 看这里stackoverflow.com/questions/1990321/date-minus-1-year。可能,是你想要的
  • 感谢 splash 但那将是去年的“日期”,我已经可以使用 subYear()
  • 你正在寻找更简单的方法:) 我已经在我的答案中写了它
  • 代码有问题。阅读我的更新以回答

标签: php datetime php-carbon


【解决方案1】:

更简单的事情

date('Y-m-d', strtotime('last year'))

【讨论】:

    【解决方案2】:

    让它更容易:)

    echo date('Y-m-d (l, W)', strtotime("-52 week"));
    

    编辑:我忘了写输出::)

    2014-05-07 (Wednesday, 19)
    

    更新 2:

    jeromegamez 的代码有问题。一年可以包含 52 或 53 周。 2016 年 1 月 3 日拍摄:

    $today = new \DateTime();
    $today->setDate ( 2016 , 1 , 3 );
    
    $year  = (int) $today->format('Y');
    $week  = (int) $today->format('W'); // Week of the year
    $day   = (int) $today->format('w'); // Day of the week (0 = sunday)
    
    $sameDayLastYear = new \DateTime();
    $sameDayLastYear->setISODate($year - 1, $week, $day);
    
    echo "Today: ".$today->format('Y-m-d (l, W)').PHP_EOL;
    echo "Same week and day last year: ".$sameDayLastYear->format('Y-m-d (l, W)').PHP_EOL;
    

    结果是:

    Today: 2016-01-03 (Sunday, 53) 
    Same week and day last year: 2015-12-27 (Sunday, 52)
    

    只有五天而不是几年:)

    【讨论】:

    • 是的,我一直在研究这个问题,并试图决定我们是否想让日期值在更长的年份移动,以便看到
    • 远没有你想象的那么好。设置日期$today->setDate ( 2016 , 1 , 3 ); 您收到Today: 2016-01-03 (Sunday, 53) Same week and day last year: 2015-12-27 (Sunday, 52)。只有五天而不是几年:)
    • 往前看 52 周似乎更好:)
    【解决方案3】:

    对于使用 Carbon 的其他人,您可以对 splash's 执行类似的解决方案,并且只需:

    Carbon::now()->subWeeks(52)
    

    2014-05-07 14:11:48

    【讨论】:

    • 请记住,有些年份有 53 周
    【解决方案4】:

    我认为DateTime::setISODate() 正是您所需要的:

    $today = new \DateTime();
    
    $year  = (int) $today->format('Y');
    $week  = (int) $today->format('W'); // Week of the year
    $day   = (int) $today->format('w'); // Day of the week (0 = sunday)
    
    $sameDayLastYear = new \DateTime();
    $sameDayLastYear->setISODate($year - 1, $week, $day);
    
    echo "Today: ".$today->format('Y-m-d (l, W)').PHP_EOL;
    echo "Same week and day last year: ".$sameDayLastYear->format('Y-m-d (l, W)').PHP_EOL;
    

    输出(今天,2015-05-05):

    Today: 2015-05-05 (Tuesday, 19)
    Same week and day last year: 2014-05-06 (Tuesday, 19)
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 2010-12-18
      • 2015-07-09
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      相关资源
      最近更新 更多