5

I need to convert a string into date format, but it's returning a weird error. The string is this:

21 nov 2012

I used:

$time = strtotime('d M Y', $string);

PHP returned the error:

Notice:  A non well formed numeric value encountered in index.php on line 11

What am I missing here?

Dênis Montone
  • 581
  • 2
  • 7
  • 18
  • 1
    You should look into [`DateTime::createFromFormat()`](http://www.php.net/manual/en/datetime.createfromformat.php); example: http://codepad.viper-7.com/0b0edk. This allows you to set exactly the format you're expecting, saving you from `strtotime()`'s nonsensical parsing of American mm-dd style dates - an inhumanely stupid format if you think about it. – NullUserException Nov 30 '12 at 18:05

4 Answers4

9

You're calling the function completely wrong. Just pass it

$time = strtotime('21 nov 2012')

The 2nd argument is for passing in a timestamp that the new time is relative to. It defaults to time().

Edit: That will return a unix timestamp. If you want to then format it, pass your new timestamp to the date function.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
2

To convert a date string to a different format:

<?php echo date('d M Y', strtotime($string));?>

strtotime parses a string returns the UNIX timestamp represented. date converts a UNIX timestamp (or the current system time, if no timestamp is provided) into the specified format. So, to reformat a date string you need to pass it through strtotime and then pass the returned UNIX timestamp as the second argument for the date function. The first argument to date is a template for the format you want.

Click here for more details about date format options.

Skylar Ittner
  • 802
  • 11
  • 26
Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26
1

You are using the wrong function, strtotime only return the amount of seconds since epoch, it does not format the date.

Try doing:

$time = date('d M Y', strtotime($string));
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • Initially, -1 for trying to get an extremely poor FGITW answer in. Downvote stays because it doesn't answer the question. – NullUserException Nov 30 '12 at 18:01
  • @NullUserException sorry about that. I was in the process of typing and it submitted.... – Naftali Nov 30 '12 at 18:01
  • 1
    All your code does is spit the input string back out as `21 Nov 2012` which is not particularly useful. OP seems to want a date format that can be used for computation, not presentation. – Sammitch Nov 30 '12 at 18:32
1

For more complex string, use:

$datetime = DateTime::createFromFormat("d M Y H:i:s", $your_string_here);
$timestamp = $datetime->getTimestamp();
Joakim Ling
  • 1,044
  • 1
  • 8
  • 13