tags:

views:

89

answers:

4

Hello,

I would like 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.

+4  A: 

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;
Malfist
Instead of using `strtotime('-1 second')` you can just subtract `1`, since you're already working with seconds.
nikc
@nickc You could, but doing the full `-1 second` makes it more readable later on, and ensures it's harder to break
Slokun
+4  A: 

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')));
Alexander Konstantinov
Yes, I'm using setcookie. This is a nice solution, thank you.
Psyche
It would be nice, but it doesn't work. With the param in the example, `strtotime` returns false. But the example does show how you can be creative with `strotime`, just not quite that conversational :-)
nikc
@nikc, seems like this example works only in PHP 5.3, but not in 5.2
Alexander Konstantinov
@Alex: that may be, my ISP hasn't upgraded yet, so neither have I. I've learned that upgrading too fast (read: depending on the cutting edge) will get you into trouble in the "real world" :-)
nikc
A: 

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();
nikc
A: 

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
evolve
DateInterval's `%d * 86400` is not exact though as it will only take the difference in days and omits h,i,s. It's easier to just do `$eom = new DateTime('last day 23:59:59'); echo $eom->format('U') - time();` when you want to use DateTime API for that.
Gordon
It was just quick code showing usage of the diff function.
evolve