tôi cần chức năng tương tự, ngoại trừ một chu kỳ hàng tháng (cộng tháng, trừ đi 1 ngày). Sau khi tìm kiếm S.O. một thời gian, tôi đã có thể thủ này giải pháp plug-n-play:
function add_months($months, DateTime $dateObject)
{
$next = new DateTime($dateObject->format('Y-m-d'));
$next->modify('last day of +'.$months.' month');
if($dateObject->format('d') > $next->format('d')) {
return $dateObject->diff($next);
} else {
return new DateInterval('P'.$months.'M');
}
}
function endCycle($d1, $months)
{
$date = new DateTime($d1);
// call second function to add the months
$newDate = $date->add(add_months($months, $date));
// goes back 1 day from date, remove if you want same day of month
$newDate->sub(new DateInterval('P1D'));
//formats final date to Y-m-d form
$dateReturned = $newDate->format('Y-m-d');
return $dateReturned;
}
Ví dụ:
$startDate = '2014-06-03'; // select date in Y-m-d format
$nMonths = 1; // choose how many months you want to move ahead
$final = endCycle($startDate, $nMonths); // output: 2014-07-02
Nó không hoạt động với tất cả các ngày. Ví dụ: 2013-05-31 sẽ hiển thị tháng 7 thay vì tháng tiếp theo vào tháng 6. –
Tôi nhận được sau đây, 2014-03-03 cho 2014-01-31 lý do? –
Nó không hoạt động với chuỗi này: "2014-06-19 15:00:19" –