天天看點

PHP函數運用之傳回某個日期的前一天和後一天

在上一篇文章《PHP函數運用之計算截止某年某月某日共有多少天》中,我們介紹了利用strtotime()函數計算兩個給定日期間時間差的方法。這次我們來來看看給大一個指定日期,怎麼傳回它前一天和後一天的日期。感興趣的朋友可以學習了解一下~

本文的重點是:傳回給定時間的前一天、後一天的日期。那麼要怎麼操作呢?

其實很簡單,PHP内置的strtotime() 函數就可以實作這個操作!下面來看看我的實作方法:

傳回某個日期的前一天的實作代碼

<?php

function GetTime($year,$month,$day){

$timestamp = strtotime("{$year}-{$month}-{$day}");

$time = strtotime("-1 days",$timestamp);

echo date("Y-m-d",$time)."

";

}

GetTime(2000,3,1);

GetTime(2021,1,1);

?>

輸出結果:

1.png

傳回某個日期的後一天的實作代碼

$time = strtotime("+1 days",$timestamp);

GetTime(2000,2,28);

GetTime(2021,2,28);

2.png

分析一下關鍵代碼:

strtotime() 函數有兩種用法:一種是将字元串形式的、用英文文本描述的日期時間解析為 UNIX 時間戳,一種是用來計算一些日期時間的間隔。

我們利用strtotime() 函數計算時間間隔的功能,使用strtotime("-1 days",$timestamp)和strtotime("+1 days",$timestamp)

計算出指定日期前一天和後一天的日期。

"-1 days"就是減一天,"+1 days"就是加一天;觀察規律,我們還可以根據需要擷取前N天,後N天的日期

$time1 = strtotime("-2 days",$timestamp);

$time2 = strtotime("+3 days",$timestamp);

echo date("Y-m-d",$time1)."

echo date("Y-m-d",$time2)."

GetTime(2000,3,5);

3.png

當strtotime() 函數有兩個參數時,第二個參數必須是時間戳格式。是以我們需要先使用一次 strtotime()函數将字元串形式的指定日期轉為字元串;在使用一次 strtotime()函數進行日期的加減運算,擷取算前N天和後N天的日期。

strtotime() 函數的傳回值是時間戳格式的;是以需要使用date("Y-m-d",$time)來格式化日期時間,傳回年-月-日格式的日期。

擴充知識:

其實利用strtotime() 函數,不僅可以擷取前N天和後N天日期,還可以擷取前N月和後N月日期、前N年和後N年日期:

$month1 = strtotime("-1 months",strtotime("2000-1-2"));

$month2 = strtotime("+2 months",strtotime("2000-1-2"));

echo date("Y-m-d",$month1)."

echo date("Y-m-d",$month2)."

$year1 = strtotime("-1 years",strtotime("2000-1-2"));

$year2 = strtotime("+2 years",strtotime("2000-1-2"));

echo date("Y-m-d",$year1)."

echo date("Y-m-d",$year2)."

4.png

想要擷取前一周和後一周的日期,也可以利用strtotime() 函數。例如:目前日期2021-8-19,前一周和後一周的日期為:

6.png

實作代碼:

header("content-type:text/html;charset=utf-8");

$start = time(); //擷取目前時間的時間戳

echo "目前日期為:".date('Y-m-d',$start)."

$interval = 7 24 3600; //一周總共的秒數

$previous_week = $start - $interval; //目前時間的時間戳 減去 一周總共的秒數

$next_week = $start + $interval; //目前時間的時間戳 加上 一周總共的秒數

echo "前一周日期為:".date('Y-m-d',$previous_week)."

echo "後一周日期為:".date('Y-m-d',$next_week)."

5.png

前後兩個日期正好相差 7 天。這其實就是計算時間差的一種逆運用。

好了就說到這裡了,有其他想知道的,可以點選這個哦。→ →php視訊教程

以上就是PHP函數運用之傳回某個日期的前一天和後一天的詳細内容,更多請關注

富貴論壇

www.fgba.net其它相關文章!