因此,在PHP中,我试图根据一周的同一天返回去年的日期值.EX :(星期一)2011-12-19输入应该返回(星期一)2010-12-20.
我只是简单地用-364来做,但那时闰年就失败了.我遇到了另一个功能:
$newDate = $_POST['date'];
$newDate = strtotime($newDate);
$oldDate = strtotime('-1 year',$newDate);
$newDayOfWeek = date('w',$oldDate);
$oldDayOfWeek = date('w',$newDate);
$dayDiff = $oldDayOfWeek-$newDayOfWeek;
$oldDate = strtotime("$dayDiff days",$oldDate);
echo 'LAST YEAR DAY OF WEEK DATE = ' . date('Ymd', $oldDate);
Run Code Online (Sandbox Code Playgroud)
但是,当您尝试输入星期日日期时失败,因为它在0(星期日)减去6(去年日期的星期六)时返回,并返回值为T-6.IE输入2011-12-25让你2010-12-19而不是2011-12-26.
我有点难以在php中找到一个好的解决方案,它可以在闰年工作,显然是一周中的所有日子.
有什么建议?
谢谢!
怎么样,使用PHP的DateTime功能:
$date = new DateTime('2011-12-25'); // make a new DateTime instance with the starting date
$day = $date->format('l'); // get the name of the day we want
$date->sub(new DateInterval('P1Y')); // go back a year
$date->modify('next ' . $day); // from this point, go to the next $day
echo $date->format('Ymd'), "\n"; // ouput the date
Run Code Online (Sandbox Code Playgroud)