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;
?>输出结果:
立即学习“PHP免费学习笔记(深入)”;

说明:
strtotime() 函数将任何英文文本的日期或时间描述解析为 Unix 时间戳(自 January 1 1970 00:00:00 GMT 起的秒数)。
PHP date() 函数可把时间戳格式化为可读性更好的日期和时间。
Y - 年份的四位数表示
m - 月份的数字表示(从 01 到 12)
推荐学习:《PHP视频教程》
以上就是php怎么计算指定日期间相差几个月的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号