簡體   English   中英

如何在 php 中獲取上個月的日期范圍

[英]how to get previous month date range in php

我想用 PHP 獲得前幾個月的日期范圍。 我已經嘗試在 function 下面獲取上個月的日期范圍。

$last_month_start_date = date('Y-m-d',strtotime('first day of last month'));
$last_month_end_date = date('Y-m-d',strtotime('last day of last month'));
echo $last_month_start_date.' - '.$last_month_end_date;

Output: 2019-09-01 - 2019-09-30

但是如何使用 PHP 獲取上個月的日期范圍?

有人可以幫我嗎?

要獲得最后一個月:如果當前月份是October ,則 output 下面給出August的第一個和最后一個日期

$last_to_last_start_date = $last_month_start_date = date('Y-m-d',strtotime('first day of last month -1 month')); 
// outout 2019-08-01

$last_to_last_end_date = $last_month_end_date = date('Y-m-d',strtotime('last day of last month -1 month')); 
// outout 2019-08-31

echo $last_to_last_start_date .' - '.$last_to_last_end_date ;
//Output : 2019-08-01 - 2019-08-31 

創建一個落后兩個月的日期時間 object,然后使用first/last day of this month的修飾符。 this month修飾符適用於 object 月份,因此如果對象的日期是八月,它將查找八月的第一天和最后一天。

這意味着您可以提供-2 months的任何值(例如February , -1 month ),它將獲得該月的開始日期和結束日期。

$start = new DateTime("-2 months");
$end = clone $start;
$start->modify("first day of this month");
$end->modify("last day of this month");
echo $start->format("Y-m-d")." - ".$end->format("Y-m-d");

在 2019 年 10 月,這輸出,

2019-08-01 - 2019-08-31

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM