在上一篇文章《PHP函數(shù)運用之計算截止某年某月某日共有多少天》中,我們介紹了利用strtotime()函數(shù)計算兩個給定日期間時間差的方法。這次我們來來看看給大一個指定日期,怎么返回它前一天和后一天的日期。感興趣的朋友可以學(xué)習(xí)了解一下~
本文的重點是:返回給定時間的前一天、后一天的日期。那么要怎么操作呢?
其實很簡單,PHP內(nèi)置的strtotime() 函數(shù)就可以實現(xiàn)這個操作!下面來看看我的實現(xiàn)方法:
-
返回某個日期的前一天的實現(xiàn)代碼
<?php function GetTime($year,$month,$day){ $timestamp = strtotime("{$year}-{$month}-{$day}"); $time = strtotime("-1 days",$timestamp); echo date("Y-m-d",$time)."<br>"; } GetTime(2000,3,1); GetTime(2021,1,1); ?>
輸出結(jié)果:
-
返回某個日期的后一天的實現(xiàn)代碼
<?php function GetTime($year,$month,$day){ $timestamp = strtotime("{$year}-{$month}-{$day}"); $time = strtotime("+1 days",$timestamp); echo date("Y-m-d",$time)."<br>"; } GetTime(2000,2,28); GetTime(2021,2,28); ?>
輸出結(jié)果:
分析一下關(guān)鍵代碼:
-
strtotime() 函數(shù)有兩種用法:一種是將字符串形式的、用英文文本描述的日期時間解析為 UNIX 時間戳,一種是用來計算一些日期時間的間隔。
-
我們利用strtotime() 函數(shù)計算時間間隔的功能,使用
strtotime("-1 days",$timestamp)
和strtotime("+1 days",$timestamp)
計算出指定日期前一天和后一天的日期。"
-1 days
"就是減一天,"+1 days
"就是加一天;觀察規(guī)律,我們還可以根據(jù)需要獲取前N天,后N天的日期
<?php function GetTime($year,$month,$day){ $timestamp = strtotime("{$year}-{$month}-{$day}"); $time1 = strtotime("-2 days",$timestamp); $time2 = strtotime("+3 days",$timestamp); echo date("Y-m-d",$time1)."<br>"; echo date("Y-m-d",$time2)."<br>"; } GetTime(2000,3,5); ?>
-
當(dāng)strtotime() 函數(shù)有兩個參數(shù)時,第二個參數(shù)必須是時間戳格式。所以我們需要先使用一次 strtotime()函數(shù)將字符串形式的指定日期轉(zhuǎn)為字符串;在使用一次 strtotime()函數(shù)進行日期的加減運算,獲取算前N天和后N天的日期。
-
strtotime() 函數(shù)的返回值是時間戳格式的;所以需要使用
date("Y-m-d",$time)
來格式化日期時間,返回年-月-日
格式的日期。
擴展知識:
-
其實利用strtotime() 函數(shù),不僅可以獲取前N天和后N天日期,還可以獲取前N月和后N月日期、前N年和后N年日期:
<?php $month1 = strtotime("-1 months",strtotime("2000-1-2")); $month2 = strtotime("+2 months",strtotime("2000-1-2")); echo date("Y-m-d",$month1)."<br>"; echo date("Y-m-d",$month2)."<br><br>"; $year1 = strtotime("-1 years",strtotime("2000-1-2")); $year2 = strtotime("+2 years",strtotime("2000-1-2")); echo date("Y-m-d",$year1)."<br>"; echo date("Y-m-d",$year2)."<br>"; ?>
輸出結(jié)果:
-
想要獲取前一周和后一周的日期,也可以利用strtotime() 函數(shù)。例如:當(dāng)前日期2021-8-19,前一周和后一周的日期為:
實現(xiàn)代碼:
<?php header("content-type:text/html;charset=utf-8"); $start = time(); //獲取當(dāng)前時間的時間戳 echo "當(dāng)前日期為:".date('Y-m-d',$start)."<br />"; $interval = 7 * 24 * 3600; //一周總共的秒數(shù) $previous_week = $start - $interval; //當(dāng)前時間的時間戳 減去 一周總共的秒數(shù) $next_week = $start + $interval; //當(dāng)前時間的時間戳 加上 一周總共的秒數(shù) echo "前一周日期為:".date('Y-m-d',$previous_week)."<br />"; echo "后一周日期為:".date('Y-m-d',$next_week)."<br />"; ?>
輸出結(jié)果:
前后兩個日期正好相差 7 天。這其實就是計算時間差的一種逆運用。
好了就說到這里了,有其他想知道的,可以點擊這個哦?!?→php視頻教程