Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
893 views
in Technique[技术] by (71.8m points)

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

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');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<?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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...