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