23

I have this string: "13/10 15:00" and I would like to convert it to timestamp but when I do this:

      $timestamp = strtotime("13/10 15:00");

It returns an empty value.

Lajos Veres
  • 13,595
  • 7
  • 43
  • 56
user2876368
  • 667
  • 2
  • 6
  • 7
  • strtotime isn't infallible - if you know the format, you should use [DateTime::createFromFormat](http://php.net/manual/en/datetime.createfromformat.php) (available from PHP 5.3.x and above) or similar. (You'll also need to provide the missing year.) – John Parker Oct 13 '13 at 15:29
  • Your format is not supported! http://www.php.net/manual/en/datetime.formats.compound.php – WebNovice Oct 13 '13 at 15:29
  • your string is not a well defined date or time – Jonas Stein Oct 13 '13 at 15:45
  • and you can use this `Carbon::create(2022, 1, 21, 10, 00, 00)` – Azade Dec 25 '21 at 05:22

2 Answers2

54

In your code strtotime() is attempting to convert 13/10 as the tenth day of the 13th month, which returns an error.

If you want to parse a date string with a custom format, it's better to use DateTime::createFromFormat() instead:

$dtime = DateTime::createFromFormat("d/m G:i", "13/10 15:00");
$timestamp = $dtime->getTimestamp();
Glavić
  • 42,781
  • 13
  • 77
  • 107
  • `$timestamp` variable contains DateTime object, not timestamp. To get timestamp, use `$timestamp->getTimestamp();` or `$timestamp->format('U');` – Glavić Oct 14 '13 at 07:19
  • @Glavić True enough - still more reliable than `strtotime()`. Thanks. –  Oct 14 '13 at 08:06
  • 7
    Link to documentation: http://php.net/manual/en/datetime.createfromformat.php – Doug Apr 18 '15 at 08:50
28
  $timestamp = strtotime("13-10-2013 15:00");

This can be important:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

http://uk3.php.net/strtotime

Lajos Veres
  • 13,595
  • 7
  • 43
  • 56