PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

青灯夜游
青灯夜游 原创
2021-10-27 18:49:43 4398浏览

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

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

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

具体实现方法如下:

<?php
header("Content-type:text/html;charset=utf-8");
$strtotime1=strtotime(&#39;2021-01-06&#39;);
$strtotime2=strtotime(&#39;2021-10-06&#39;);
$y=date(&#39;Y&#39;,$strtotime1);
$ys=date(&#39;Y&#39;,$strtotime2);
$m=(int)date(&#39;m&#39;,$strtotime1);
$ms=(int)date(&#39;m&#39;,$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视频教程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。