使用php查找2个月后的日期
当我得知当前日期为“2017年12月31日”时。我需要找到2个月后的日期,也就是2月。2月份时,我需要获得“29/2/2018”。但当我们使用下面的代码时,我得到了“03/03/2018”。你能帮我解决这个任务吗 这里我添加了我的PHP代码使用php查找2个月后的日期,php,Php,当我得知当前日期为“2017年12月31日”时。我需要找到2个月后的日期,也就是2月。2月份时,我需要获得“29/2/2018”。但当我们使用下面的代码时,我得到了“03/03/2018”。你能帮我解决这个任务吗 这里我添加了我的PHP代码 $xmasDay = new DateTime('2017-12-31 + 2 month'); echo $xmasDay->format('Y-m-d'); 请试试这个 <?php function add_month($date_s
$xmasDay = new DateTime('2017-12-31 + 2 month');
echo $xmasDay->format('Y-m-d');
请试试这个
<?php
function add_month($date_str, $months)
{
$date = new DateTime($date_str);
// We extract the day of the month as $start_day
$start_day = $date->format('j');
// We add 1 month to the given date
$date->modify("+{$months} month");
// We extract the day of the month again so we can compare
$end_day = $date->format('j');
if ($start_day != $end_day)
{
// The day of the month isn't the same anymore, so we correct the date
$date->modify('last day of last month');
}
return $date->format('Y-m-d');
}
$result = add_month('2017-12-31', 2);
echo $result
请试试这个
<?php
function add_month($date_str, $months)
{
$date = new DateTime($date_str);
// We extract the day of the month as $start_day
$start_day = $date->format('j');
// We add 1 month to the given date
$date->modify("+{$months} month");
// We extract the day of the month again so we can compare
$end_day = $date->format('j');
if ($start_day != $end_day)
{
// The day of the month isn't the same anymore, so we correct the date
$date->modify('last day of last month');
}
return $date->format('Y-m-d');
}
$result = add_month('2017-12-31', 2);
echo $result
从月初开始计算,然后使用日期t
$orginal = '2017-12-31';
$orginal = explode('-', $orginal);
$originalDate = strtotime($orginal[0] . '-' . $orginal[1] . '-01 00:00:00');
$newDate = strtotime('+2 month', $originalDate);
echo date('Y-m-t', $newDate);
// or
$date = new DateTime();
$date->setTimestamp($newDate);
echo $date->format('Y-m-t');
从月初开始计算,然后使用日期t
$orginal = '2017-12-31';
$orginal = explode('-', $orginal);
$originalDate = strtotime($orginal[0] . '-' . $orginal[1] . '-01 00:00:00');
$newDate = strtotime('+2 month', $originalDate);
echo date('Y-m-t', $newDate);
// or
$date = new DateTime();
$date->setTimestamp($newDate);
echo $date->format('Y-m-t');
快速回答:没有2018年2月29-30-31日,所以PHP将切换到2018年3月3日。你可以在这里找到答案:快速回答:没有2018年2月29-30-31日,所以PHP改为2018年3月3日。你可以在这里找到答案:如果我的答案解决了你的问题,请勾选我的答案@dhinesh balu;如果我的答案解决了你的问题,请勾选我的答案@dhinesh balu