Nanny Boy
Nanny Boy

Reputation: 107

php datetime output issue

I fetch datetime in the DB from different columns based on some conditions.

The script in PHP:

if($obj->acct_status == 2)
    $dt = date('d M, Y h:i:s A', strtotime($obj->approve_datetime));

if($obj->acct_status == 4)
    $dt = date('d M, Y h:i:s A', strtotime($obj->suspend_datetime)); 

The DB stores datetime in this format:

2016-11-11 14:26:03

The output:

30 Nov, -0001 12:00:00 AM

What is the cause of this issue?

Upvotes: 0

Views: 124

Answers (1)

Xorifelse
Xorifelse

Reputation: 7911

I strongly believe strtotime() should be avoided when there is a format available.

$from_format = 'Y-m-d H:i:s';
$to_format   = 'd M, Y h:i:s A';
$date = '2016-11-11 14:26:03';        


echo DateTime::createFromFormat($from_format, $date)->format($to_format);

Outputs:

11 Nov, 2016 02:26:03 PM

Why your code fails I cannot say for certain, it works fine here but you can diagnose a little. I'm assuming in your case its because strtotime() fails converting, returning -62169984000 which is actually 0000-00-00 00:00:00 but due to a second, minute, day and a month that is not allowed to be 0, calculations occur resulting in 0000-00-00 00:00:00 minus 1 day and 1 month, etc being 30 Nov -0001 12:00:00 so it would appear your $obj->suspend_datetime does not contain the correct data.


I've written 2 small functions to share that would make this whole ordeal easier to handle:

function strtodatetime($date, $format = 'Y-m-d H:i:s'){
  return ($d = DateTime::createFromFormat($format, $date)) && $d->format($format) == $date ? $d : false;
}

function strtounixtime($date, $format = 'Y-m-d H:i:s'){
  return ($d = DateTime::createFromFormat($format, $date)) && $d->format($format) == $date ? $d->getTimestamp() : 0;
}

echo ($dt = strtodatetime($date)) ? $dt->format($to_format) : 'invalid format';
echo date('d M, Y h:i:s A', strtounixtime($obj->approve_datetime));

In your scenario, using strtounixtime() (a better strtotime()) it would translate back to the unix epoch if it fails.

Upvotes: 4

Related Questions