How to calculate the number of months between a specified date in PHP

青灯夜游
Release: 2023-03-13 14:24:01
Original
4755 people have browsed it

How to calculate the difference in months in php: 1. Use the strtotime() function to convert two specified dates into timestamp form; 2. Use the "date('m', timestamp)" statement to obtain The months of the two specified dates; 3. Subtract the two obtained months to calculate the difference in months.

How to calculate the number of months between a specified date in PHP

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php calculates the difference between specified dates Month

The specific implementation method is as follows:

<?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;
?>
Copy after login

Output result:

How to calculate the number of months between a specified date in PHP

Instructions:

# The ##strtotime() function parses any English text date or time description into a Unix timestamp (number of seconds since January 1 1970 00:00:00 GMT).

PHP date() function can format the timestamp into a more readable date and time.

  • Y - Four-digit representation of the year

  • m - Numeric representation of the month (from 01 to 12)

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to calculate the number of months between a specified date in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template