How can i parse a date to same day of previous month?

浪尽此生 提交于 2019-12-14 03:59:05

问题


How can i parse a date to same day of previous month in PHP?

Example:

   input                 Output

2018-07-25     ->       2018-06-25
2018-07-31     ->       2018-06-30 (because there is no 31)

My code

$d = "2018-07-25";
$xd = date_parse_from_format("y-m-d", $d last month);
$output_d = date_create($xd)->format('Y-m-d');

回答1:


<?php
$date = new DateTimeImmutable("2018-07-31");
$previous = $date->sub(new DateInterval('P1M'));
$lastMonth= $date->modify('last day of previous month');
if ($previous > $lastMonth) {
    $previous = $lastMonth;
}
echo $previous ->format('Y-m-d');

This code subtracts one month from the current date. If it is greater than the last day of the previous month we use the last day of the previous month instead.

Demo




回答2:


Going back to one month is like subtracting one month from the existing date so with the help of strtotime and date we can solve this. like,

$a = "2018-07-25"; $b = date("Y-m-d",strtotime($a."-1 month")); $b is 2018-06-25

Hope this helps.



来源:https://stackoverflow.com/questions/51285654/how-can-i-parse-a-date-to-same-day-of-previous-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!