所以我现在正在使用Carbon来获取日期,时间和比较。去年我可以很容易地做subYear()以获得 date 。现在我需要一些东西在去年的同一时间得到完全相同的天,例如4月的第二周的星期三。
我希望必须做一些能在本周的当天工作的事情,例如3,以及今年的当前一周,然后去年获得相同的价值。
以为我会检查在Carbon或其他PHP工具中是否有可用的功能?感谢
答案 0 :(得分:5)
我认为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)
答案 1 :(得分:2)
让它变得更容易:)
echo date('Y-m-d (l, W)', strtotime("-52 week"));
编辑:我忘了写输出:: :)
2014-05-07 (Wednesday, 19)
<强> UPDATE2:强>
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)
只有五天而不是几年:)
答案 2 :(得分:1)
对于其他使用Carbon的人来说,你可以做一个类似于splash的解决方案,只需要:
Carbon::now()->subWeeks(52)
给出2014-05-07 14:11:48
答案 3 :(得分:1)
更简单的事情<3
date('Y-m-d', strtotime('last year'))