tags:

views:

289

answers:

6

Hi,

I am using date function along with strtotime function to format the date.

Ex:

<?php
$input_date = '03-JUL-09 14:53';

$formatted_date =  date("Y-m-d H:i:s", strtotime($input_date));

echo $formatted_date;
?>

Gives me a expected output: 2009-07-03 14:53:00

while if the input is changed to(I am removing the minute part)-

<?php
$input_date = '03-JUL-09 14';

$formatted_date =  date("Y-m-d H:i:s", strtotime($input_date));

echo $formatted_date;
?>

The output here is 1970-01-01 05:30:00, which is not at all expected.

Whats the mistake I am doing and how it can be fixed.

Thanks

Amit

A: 

1970-01-01 is a typical baseline date (in ctime for example). I believe the output is formatting a value of 0 into a date, thus the 1970, and the unrelated 05:30:00 time of day.

I believe this is a fluke in attempting to format a date that does not include all the requested time elements. Can you pad the date data to generate a complete input date?

pianoman
A: 

strtotime() fails to parse the second string when you remove the minute part. It doesn't know what the extra "14" means so it returns bool(false). Calling date(false) returns the same thing as date(0), i.e. it gives you the date of the UNIX epoch: January 1, 1970 00:00:00 GMT adjusted for your local timezone.

John Kugelman
A: 

This looks like it comes down to the inability of strtotime() to determine which numbers are what in your 2nd date string.

My best advice is to normalize your date-time value before passing it to strtotime(). Something simple like this might be enough

if ( false === strpos( $input_date, ':' ) )
{
  $input_date .= ':00';
}
Peter Bailey
+1  A: 

03-JUL-09 14 does not seem to be a valid date string, 03-JUL-09 14:00 works fine

from the php manual: strtotime — Parse about any English textual datetime description into a Unix timestamp

smoove666
A: 

1970-01-01 05:30:00 is the time in India at the Unix epoch (1970-01-01 00:00:00 GMT/UTC). This means that strtotime returned either 0, or false, which was converted to 0 by date. This is because it could not process its input, as others have explained.

Samir Talwar
+1  A: 

Hi,

The function strtotime expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp. You can use strings like

  • 03 july 2009
  • now
  • 09-07-03
  • 09-07-03 14:00:00
  • +1 week 2 days 4 hours 2 seconds
  • last Monday

But not incomplete date format like "09-07-03 14". The parser don't understand it and returns nothing so when you call date("Y-m-d H:i:s", strtotime($input_date)); it returns the 0 timestamp (January 1 1970 00:00:00 UTC), cause it's the default value.

You have to give a right string that can be parsed.

Timothée Martin
Thanks Everyone..
Amit