12

Is there a function that uses the date() format to interpret a string?

echo date('s-i-H d:m:Y', 1304591364); // 34-29-17 05:05:2011

// Does this function exist?
echo inverse_date('s-i-H d:m:Y', '34-29-17 05:05:2011'); // 1304591364

I know strtotime(), but it’s failing me in most cases as I am not parsing English date formats.

I’m looking for a function that can dictate the format.

7 Answers 7

13

The real answer to this question the way I mean it is http://www.php.net/manual/en/datetime.createfromformat.php

    $date = date_create_from_format('j-M-Y', '15-Feb-2009');
    echo date_format($date, 'Y-m-d'); // 2009-02-15
2
  • 2
    Only in PHP 5.3, unfortunately.
    – cam8001
    Commented May 9, 2011 at 16:38
  • Alternative syntax: $date = \DateTime::createFromFormat($format, $var)
    – Alsciende
    Commented Apr 3, 2012 at 9:28
9

You would typically use strtotime for that:

echo strtotime('2011-05-05 17:29:34');

From the manual:

strtotime — Parse about any English textual datetime description into a Unix timestamp

See valid date and time formats to be sure that the string you are passing in will be parsed correctly.

1
  • Sorry, I forgot to mention that I used strtotime, but as I am not based in the US, I need to control the formats
    – Moak
    Commented May 5, 2011 at 9:41
4

PHP 5.4+ will print 1359674625

echo date_create_from_format('j/n/Y G:i:s','1/2/2013 1:23:45')->getTimestamp();
1
  • This is the actual correct way to do it, i.e. using the DateTime object
    – efx
    Commented May 16, 2016 at 18:41
1

The function mktime seems to do what you want.

Check the help over at php.net:

http://php.net/manual/en/function.mktime.php

EDIT : indeed strtotime may be more convenient for you, I did not know that function, glad to learn.

1

The accepted answer is right IMO, but you can also use the OO syntax: DateTime::createFromFormat eg:

$dateTimeObject = \DateTime::createFromFormat('G:i', '9:30');
$dateTimeObject->format('H:i');

See http://php.net/manual/en/function.date.php for formatting guides, and http://php.net/manual/en/datetime.createfromformat.php for info on the method described above.

0

Yes you can use:

echo strtotime("2011-05-05 17:29:34");
2
  • see edit, I'm looking for the function that can dictate the format
    – Moak
    Commented May 5, 2011 at 9:43
  • you can use regex to validate format of your date. something like this /^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}$/
    – Headshota
    Commented May 5, 2011 at 9:53
0

Try this to reverse:

$x = '2013-09-15';

$x = implode('-', array_reverse(explode('-', $x)));

// now $x = '15-09-2013'

1
  • 1
    nice, however I didn't mean I wanted to reverse the order :)
    – Moak
    Commented Sep 23, 2013 at 1:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.