5

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

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

只是想我会检查在 Carbon 或其他 PHP 工具中是否有任何可用的东西?谢谢

4

4 回答 4

7

我认为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)
于 2015-05-05T17:25:55.777 回答
3

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

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

2014-05-07 14:11:48

于 2015-05-06T13:13:30.843 回答
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)

只有五天而不是几年:)

于 2015-05-06T10:09:43.780 回答
2

更简单的事情<3

date('Y-m-d', strtotime('last year'))
于 2020-06-19T02:40:10.657 回答