php計(jì)算相差幾個(gè)月的方法:1、使用strtotime()函數(shù)將兩個(gè)指定日期轉(zhuǎn)換為時(shí)間戳形式;2、使用“date('m',時(shí)間戳)”語句獲取到兩個(gè)指定日期的月份;3、將獲取到的兩個(gè)月份相減即可計(jì)算出相差幾個(gè)月。
本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版、DELL G3電腦
php計(jì)算指定日期間相差幾個(gè)月
具體實(shí)現(xiàn)方法如下:
<?php header("Content-type:text/html;charset=utf-8"); $strtotime1=strtotime('2021-01-06'); $strtotime2=strtotime('2021-10-06'); $y=date('Y',$strtotime1); $ys=date('Y',$strtotime2); $m=(int)date('m',$strtotime1); $ms=(int)date('m',$strtotime2); $chaY=$ys-$y; //月份相差多少 $chaM=12-$m + $ms; //相差一年就加12 $yearmeth=$chaM + (($chaY-1) *12); echo $yearmeth; ?>
輸出結(jié)果:
說明:
strtotime() 函數(shù)將任何英文文本的日期或時(shí)間描述解析為 Unix 時(shí)間戳(自 January 1 1970 00:00:00 GMT 起的秒數(shù))。
PHP date() 函數(shù)可把時(shí)間戳格式化為可讀性更好的日期和時(shí)間。
-
Y – 年份的四位數(shù)表示
-
m – 月份的數(shù)字表示(從 01 到 12)
推薦學(xué)習(xí):《PHP視頻教程》