Get seconds until the end of the month in PHP
I would 开发者_如何学Pythonlike to set a cookie with PHP that has to expire at the end of the month.
How can I get the number of seconds until the end of the month?
Thank you.
You can use time() to get the number of seconds elapsed since the epoche. Then use strtotime("date") to get the number of seconds to your date. Subtract the two and you have the number of seconds difference.
This will give you the last second of the month:
$end = strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00')) - 1;
This will give you now:
$now = time();
This will give you the distance:
$numSecondsUntilEnd = $end - $now;
If you're using setcookie() function, then you don't really need the number of seconds, you need the timestamp, when cookie should be expired:
// Works in PHP 5.3+
setcookie("cookie_name", "value", strtotime("first day of next month 0:00"));
// Example without using strtotime(), works in all PHP versions
setcookie("cookie_name", "value", mktime(0, 0, 0, date('n') + 1, 1, date('Y')));
In PHP 5.3 they added a DateTime class which makes handling operations like this make a lot more sense and a little bit easier too (in my opinion).
$datetime1 = new DateTime('now'); // current date
$datetime2 = new DateTime(date("Ymt")); // last day in the month
$interval = $datetime1->diff($datetime2); // difference
echo $interval->format('%d') * 86400; // number of seconds
Create a timestamp for the end of the month and subtract the timestamp for the current time from it.
// Create a timestamp for the last day of current month
// by creating a date for the 0th day of next month
$eom = mktime(0, 0, 0, date('m', time()) + 1, 0);
// Subtract current time for difference
$diff = $eom - time();
精彩评论