Karem
Karem

Reputation: 18123

Adding months to timestamp in PHP

        $bought_months = 6;
        $currentDate = date('Y-m-d');
        $expiring = strtotime('+'.$bought_months.' month', $currentDate); 

This is what i tried.

I am trying to get a unix timestamp value of 6 months ahead from today.

How can i add months to my unix timestamp right? I tried above, since my other thought - calculating by seconds like one month in seconds: 2 629 743.83 * how many months + current timestamp, will not be precise.

(ofcourse because months have different number of days)

I get "A non well formed numeric value encountered" for the code above.

How can i do this?

Upvotes: 1

Views: 5364

Answers (3)

Suhail Patel
Suhail Patel

Reputation: 13694

Since you are using the current timestamp, you can omit the $currentDate variable altogether and it should make the notice go away too.

    $bought_months = 6;
    $expiring = strtotime('+'.$bought_months.' month'); 

Upvotes: 3

Maerlyn
Maerlyn

Reputation: 34125

For maximum compatibility with post-2038 dates, use php's builtin DateTime class:

$d = new DateTime();
$d->modify("+6 months");
echo $d->format("U");

Upvotes: 2

Peter Gibbons
Peter Gibbons

Reputation: 103

To make the date correctly you'd need to use something like:

mktime( 0, 0, 0, ( $month + 6 ), $day, $year );

Upvotes: 2

Related Questions