php怎么计算指定日期间相差几个月

2021-10-27 19:33:10 IT技术网 互联网
浏览

php计算相差几个月的方法:1、使用strtotime()函数将两个指定日期转换为时间戳形式;2、使用“date('m',时间戳)”语句获取到两个指定日期的月份;3、将获取到的两个月份相减即可计算出相差几个月。

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑

php计算指定日期间相差几个月

具体实现方法如下:

<?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;
?>

输出结果:

1.png

说明:

strtotime() 函数将任何英文文本的日期或时间描述解析为 Unix 时间戳(自 January 1 1970 00:00:00 GMT 起的秒数)。

PHP date() 函数可把时间戳格式化为可读性更好的日期和时间。

  • Y - 年份的四位数表示

  • m - 月份的数字表示(从 01 到 12)

推荐学习:《PHP视频教程》

以上就是php怎么计算指定日期间相差几个月的详细内容,更多请关注dnjidi.com其它相关文章!