JM4
JM4

Reputation: 6788

PHP 5.3+ DateTime class issues

I am trying to create a basic select menu using PHP variables for given dates. The date would select the 1st of the current month and subtract a given number of months to display according to other system rules. I am running into an error though and not sure why. I have broken the php out of my HTML completely just to test the class. Here are my findings:

Code

<?php 
    $date = new DateTime(date('Y').'-'.date('m').'-01'); 
    $date_now = $date->format('Y-m-d');
    $date->sub(new DateInterval('P12M'));
    $end_date = $date->format('Y-m-d');

    echo '1: '. $date_now. ' - '.strtotime($date_now).'<br />'; //works
    echo '2: '. $end_date. ' - '.strtotime($end_date).'<br />'; //works
    echo '3: '. $date_now = date("Y-m-d", strtotime("-1 month", strtotime($date_now))).'<br />'; //works
    echo '4: '. strtotime($date_now).'<br />'; //does not give any response
    echo '5: '. $date_now = date("Y-m-d", strtotime("-1 month", strtotime($date_now))).'<br />'; //does not work
    echo '6: '. $date_now; //does not work
    exit;
?>

Results

1: 2011-12-01 - 1322719200

2: 2010-12-01 - 1291183200

3: 2011-11-01

4:

5: 1969-12-01

6: 1969-12-01

As you can see - statement 4 does not echo at all and 5/6 are seemingly incorrect. Any ideas as to why this is occurring? Is it something to do with the way DateTime results are returned?

Upvotes: 2

Views: 1291

Answers (1)

liquorvicar
liquorvicar

Reputation: 6106

In your third echo you're concatenating
to the date string when you assign a new value to $date_now and this is causing strtotime() to fail on the next line.

btw, you're using the DateInterval class in the first few lines but not further down in the script. Is there any reason for that?

Also, you should invest in a debugger (ZendDebugger or xDebug are the two most popular ones). I spotted this error in about 30 seconds flat using a debugger...

EDIT: In reply to OP's comment, you can still do the while statement using the DateTime class:

while( $date_now >= $end_date ) {
   echo ...;
   $date_now->sub(new DateInterval('P1M'));
}

But you might need to make sure you clone the DateTime object when you create the end date as otherwise you'll end up looping back from 1 year ago forever...

Upvotes: 2

Related Questions