[英]Get the last day of the last month and the first day of next month in PHP
如果我有例如:
'2020-01-01'
我想要兩個日期:
- 上個月的最后一天:
'2019-12-31'
- 下個月的第一天:
'2020-02-01'
我嘗試使用類似echo date("Yn-31", strtotime('2020-01-01'));
但我不知道。
謝謝你。
使用以下代碼:
<?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
?>
使用具有用戶定義日期(自定義日期)的 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
試試這個,使用 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()
這個 php 函數將英文文本日期時間描述轉換為 UNIX 時間戳
- 上個月的最后一天:
echo date("Y-m-d", strtotime("Last day of last month"));
- 下個月的第一天:
echo date("Y-m-d", strtotime("First day of next month"));
您可以使用 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');
在這里試試: 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.