简体   繁体   English

PHP获取上个月的最后一天和下个月的第一天

[英]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' '2020-01-01'

I want to have two dates :我想要两个日期:

-The last day of the prévious month : - 上个月的最后一天:

'2019-12-31' '2019-12-31'

-The first day of next month : - 下个月的第一天:

'2020-02-01' '2020-02-01'

I tried to use something like echo date("Yn-31", strtotime('2020-01-01'));我尝试使用类似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)使用具有用户定义日期(自定义日期)的 Datetime 对象

# 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试试这个,使用 strtotime() 添加月份或减去月份

$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() strtotime()
this php function convert english textual date-time discription into UNIX timestamp这个 php 函数将英文文本日期时间描述转换为 UNIX 时间戳

  • the first step converts textual date-time into a timestamp第一步将文本日期时间转换为时间戳
  • now you have timestamp then use the date() function现在你有了时间戳,然后使用 date() 函数

-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:您可以使用 DateTime 的方法modify()来实现相对日期:

<?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在这里试试: 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)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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