Home >Backend Development >PHP Problem >PHP function application to calculate how many days there are until a certain day of a certain month of a certain year
In the previous article "How to calculate the total number of days for a given year, month and day through PHP", we introduced a method for calculating the total number of days for a given year, month and day. This time we will simplify the method and show you how to calculate the total number of days with the help of the strtotime() function.
The theme of this article is: given a year, month and day, calculate the total number of days until this day.
How to calculate this? If you don't have any ideas, let's change the direction and simplify it. Isn't it just to find the number of days between January 1st, year x - day x, month x, year x, that is, to find the time difference between the two dates. So how to find the time difference?
We need to first convert two dates: January 1, x year and x month x day, x year into timestamps
$startdate = strtotime("{$year}-01-01"); $enddate = strtotime("{$year}-{$month}-{$day}");
Then subtract the two timestamps (end time - Starting time)
$diff_seconds = $enddate-$startdate;
This will get the time difference between the two dates, but at this time it is still counted in seconds, which is not conducive to reading.
Because there are 24 hours in a day, 60 minutes in an hour, and 60 seconds in a minute; if you convert 24*60*60=86400
, there are 86,400 seconds in a day.
Divide the time difference $diff_seconds by 86400, and use floor() to round down to the nearest integer
$time = floor(($diff_seconds)/86400);
What you get at this time is the difference in days, excluding x month x day On this day, add 1 to get the total number of days up to a certain day of a certain month and year.
Let’s take a look at the complete code:
function GetDays($year,$month,$day){ $startdate = strtotime("{$year}-01-01"); $enddate = strtotime("{$year}-{$month}-{$day}"); $diff_seconds = $enddate-$startdate; $time = floor(($diff_seconds)/86400); $day = $time+1; echo "截止{$year}-{$month}-{$day} 共有 {$day} 天<br>"; }
Test it: Calculate the total number of days until 2000-3-5 (because 2000 is a leap year, so 31 29 5=65)
GetDays(2000,3,5);
The output result is:
OK, the total number of days is correct! Using the GetDays($year,$month,$day) function, we can also calculate the total number of days in a year
GetDays(2000,12,31); GetDays(2021,12,31);
The output result is:
Okay That’s it for now. If you want to know anything else, you can click here. → →php video tutorial
The above is the detailed content of PHP function application to calculate how many days there are until a certain day of a certain month of a certain year. For more information, please follow other related articles on the PHP Chinese website!