简体   繁体   中英

Get the last day of the last month and the first day of next month in PHP

If i have for example :

'2020-01-01'

I want to have two dates :

-The last day of the prévious month :

'2019-12-31'

-The first day of next month :

'2020-02-01'

I tried to use something like echo date("Yn-31", strtotime('2020-01-01')); but i don't know.

Thank you.

Use below code:

<?php

$month_end = new DateTime("last day of last month");
$month_ini = new DateTime("first day of next month");

echo $month_end->format('Y-m-d'); // will print, Last day of last month
echo $month_ini->format('Y-m-d'); // will print First day of next month

?>

With Datetime object with user defined date (Custom date)

# with datetime object
$d1 = new DateTime('2019-12-01');
$d1 -> modify('last day of last month');
echo $d1 -> format('d.m.Y'), "\n";

$d2 = new DateTime('2019-12-01');
$d2 -> modify('first day of next month');
echo $d2 -> format('d.m.Y'), "\n";

Output:
30.11.2019
01.01.2020

Try this, Use strtotime() for add month or minus month

$date='2020-01-01';
echo date("Y-m-t", strtotime('-1 month'.$date)); //2019-12-31
echo date("Y-m-01", strtotime('+1 month'.$date)); //2020-02-01

strtotime()
this php function convert english textual date-time discription into UNIX timestamp

  • the first step converts textual date-time into a timestamp
  • now you have timestamp then use the date() function

-The last day of the prévious month :

echo date("Y-m-d", strtotime("Last day of last month"));

-The first day of next month :

echo date("Y-m-d", strtotime("First day of next month"));

You can use DateTime's method modify() to achieve relative dates:

<?php

$dateOld = new \DateTimeImmutable('2020-01-01');

echo $dateOld->modify("last day of last month")->format('Y-m-d');
echo PHP_EOL;
echo $dateOld->modify("first day of next month")->format('Y-m-d');

Try it here: https://3v4l.org/qALa5

$date='2020-01-01';
echo date("Y-m-d", 'last day of previous month', strtotime($date)));
echo date("Y-m-d", 'first day of next month', strtotime($date)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM