我在数据库中有一个PHP日期,例如2011年8月8日。我已经使用strtotime()函数格式将其显示为所需的格式。
我需要调整这个日期使其变为2013年8月8日(当前年份)。请问最佳的做法是什么?目前为止,我一直在努力想但是没有成功。
迄今为止,您收到的一些答案忽略了您想要将任何给定日期更新为当前年份,并集中于将2011年变为2013年(不包括被接受的答案)。然而,我认为在这些情况下使用DateTime类的示例总是有用的。
被接受的答案会导致一个注意事项:
注意:遇到一个非格式良好的数字值......
如果您提供的日期是闰年的2月29日,则会出现此问题,尽管它仍应该给出正确的结果。
以下是一个通用函数,它将获取任何有效日期并返回相同日期的当前年份:
/**
* @param String $dateString
* @return DateTime
*/
function updateDate($dateString){
$suppliedDate = new \DateTime($dateString);
$currentYear = (int)(new \DateTime())->format('Y');
return (new \DateTime())->setDate($currentYear, (int)$suppliedDate->format('m'), (int)$suppliedDate->format('d'));
}
var_dump(updateDate('8th August 2011'));
DateTime::format()
方法,它非常有用。strtotime( date( 'd M ', $originaleDate ) . date( 'Y' ) );
这个功能会从原始时间中提取出日和月份,加上当前年份,并将其转换成新日期。您也可以添加要添加到原始时间戳的秒数。例如两年就是 63,113,852 秒。
<?php
$date = "11/08/2011";
$time = strtotime($date);
$time_future = strtotime("+2 years", $time);
$future = date("d/m/Y", $time_future);
echo "NEW DATE : " . $future;
?>
date('2013-m-d', strtotime($myTime))
$year = date('Y');
$myMonthDay = date('m-d', strtotime($myTime));
echo $year . '-' . $myMonthDay;
使用日期修改函数的方法如下:
$date = new DateTime('2011-08-08'); $date->modify('+2 years');
echo $date->format('Y-m-d') . "\n";
//将输出 "2013-08-08"