这篇文章主要整理了关于php日期时间运算相关内容,涉及知识点较为全面,感兴趣的小伙伴们可以参考一下
实例讲解之前,先来介绍几个核心函数:
mktime 函数
mktime() 函数返回一个日期的 Unix 时间戳。
参数总是表示 GMT 日期,因此 is_dst 对结果没有影响。
参数可以从右到左依次空着,空着的参数会被设为相应的当前 GMT 值。
语法:mktime(hour,minute,second,month,day,year,is_dst)
参数 描述
hour 可选。规定小时。
minute 可选。规定分钟。
second 可选。规定秒。
month 可选。规定用数字表示的月。
day 可选。规定天。
year 可选。规定年。在某些系统上,合法值介于 1901 - 2038 之间。不过在 PHP 5 中已经不存在这个限制了。
is_dst 可选。如果时间在日光节约时间(DST)期间,则设置为1,否则设置为0,若未知,则设置为-1。
自 5.1.0 起,is_dst 参数被废弃。因此应该使用新的时区处理特性。
例子:mktime() 函数对于日期运算和验证非常有用。它可以自动校正越界的输入:
输出:
Jan-05-2002 Feb-01-2002 Jan-01-2001 Jan-01-1999
strtotime 函数
strtotime() 函数将任何英文文本的日期时间描述解析为 Unix 时间戳。
语法:strtotime(time,now)
参数 描述
time 规定要解析的时间字符串。
now 用来计算返回值的时间戳。如果省略该参数,则使用当前时间。
一周之后: strtotime("+1 week") ;
一周之前: strtotime("-1 week") ;
一月之后: strtotime("+1 months") ;
一天之后: strtotime("+1 days") ;
30秒之后 strtotime( " +30 seconds " );
20分钟之后 strtotime( " +20 minutes " );
12个小时之后 strtotime( " +12 hours " );
date 函数
date() 函数格式化一个本地时间/日期。
语法
date(format,timestamp)
date_default_timezone_set 函数
date_default_timezone_set() 函数设置用在脚本中所有日期/时间函数的默认时区。
date_default_timezone_set(timezone)
实例
第一种情况是没有数据库,只是得到的日期值进行比较的话,那就得完全用php的时间日期函数计算了,如下:
比如要计算2015-9-5到2015-9-18还有多少天:
第二种 孩子的成长
***自出生($stime)以来…:
";
echo "今天是第".Lnbsp(daysofnow($stime),3)."天
";
echo "今天是第".Lnbsp(weeksofnow($stime),3)."周
";
echo "今天是第".Lnbsp(monthsofnow($stime),3)."个月
";
echo "今天是第".Lnbsp(yearsofnow($stime),3)."年
";
/*
$output=sprintf(" 今天是第%03d天
今天是第%03d周
今天是第%03d个月
今天是第%03d年
....
".date('w',$ntemp)."
";
return ($ntemp-$ftemp)/60/60/24/7;
}
function daysofnow($stime)
{
$ftime=strtotime($stime);
return ceil(abs((time()-$ftime)/(60*60*24)));
}
function monthsofnow($stime)
{
$ftime=strtotime($stime);
$fmonth=date('m',$ftime);
$fyear=date('Y',$ftime);
$nmonth=date('m');
$nyear=date('Y');
$result=($nyear-$fyear)*12+$nmonth-$fmonth+1;
return $result;
}
function yearsofnow($stime)
{
$ftime=strtotime($stime);
$fyear=date('Y',$ftime);
$nyear=date('Y');
return $nyear-$fyear+1;
}
// 下面的函数只是加空格用的,不是核心内容,只为美观
function Lnbsp($data,$num)
{
$result=trim($data);
for($i=$num;$i>=strlen($data);$i--) {
$result=' '.$result;
}
return $result;
}
?>
第三种 情况:明天,下个月和明年的日期,就可以用以下的代码:

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver Mac版
視覺化網頁開發工具

記事本++7.3.1
好用且免費的程式碼編輯器