Dênis Montone
Dênis Montone

Reputation: 621

Convert specific string to time in PHP

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?

Upvotes: 7

Views: 41650

Answers (4)

Rubin Porwal
Rubin Porwal

Reputation: 3845

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.

Upvotes: 3

Joakim Ling
Joakim Ling

Reputation: 1222

For more complex string, use:

$datetime = DateTime::createFromFormat("d M Y H:i:s", $your_string_here);
$timestamp = $datetime->getTimestamp();

Upvotes: 1

mpen
mpen

Reputation: 282805

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.

Upvotes: 10

Naftali
Naftali

Reputation: 146302

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));

Upvotes: 2

Related Questions