Home > Article > Backend Development > How to calculate the difference in weeks between two dates in php
Method: 1. Use the strtotime() function to convert two dates into timestamps; 2. Subtract the two timestamps to get the time difference; 3. Use "floor((time difference)/86400)" The statement converts the time difference into a difference in days; 4. Divide the difference in days by 7 to calculate how many weeks the difference between the two dates is.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
How does php calculate two How many weeks is the difference between two dates?
Calculating how many weeks is the difference between two dates is actually calculating the time difference between two dates.
can be obtained below The number of days difference
Then divide the number of days difference by 7
The number of days difference can be calculated using strtotime() and date()
Convert two dates to timestamps using the strtotime() function;
Then subtract the two timestamps to get the time difference , but at this time it is still counted in seconds, which is not conducive to reading.
Then divide the time difference by 86400 (24*60*60=86400), and then use floor() to round down to the nearest integer
<?php header("content-type:text/html;charset=utf-8"); function daysDiff($date1, $date2) { $first = strtotime($date1); $second = strtotime($date2); if($first>$second){ $diff_seconds=$first-$second; }else{ $diff_seconds=$second-$first; } $time = floor(($diff_seconds)/86400); return $time; } $dt1 = '2022-1-1'; $dt2 = '2022-1-15'; echo $dt1.' 和 '. $dt2. ' 之间相差的天数是 '. daysDiff($dt1, $dt2) ."天"; ?>
The difference in days is calculated, just look at the difference in weeks
$weeksDiff=daysDiff($dt1, $dt2)/7; echo $dt1.' 和 '. $dt2. ' 之间相差的周数是 '. $weeksDiff ."周";
Look at the calendar, it’s exactly two weeks.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to calculate the difference in weeks between two dates in php. For more information, please follow other related articles on the PHP Chinese website!