0

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?

2
  • see this php.net/manual/en/… Commented Nov 11, 2016 at 7:19
  • its because different default format between database and sql Commented Nov 11, 2016 at 7:23

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Can have many reasons, your code actually works here. I'm assuming strtotime() fails in your case. Try echoing its integer and use this to check if its the correct date.
Its a good approach but if you change you date with $date = '0000-00-00 00:00:00'; You will get the same output as the above question mention so why use this?
You can suggest how to validate date supplied before converting :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.