Convert specific string to time in PHP
Solution 1
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.
Solution 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.
Solution 3
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));
Solution 4
For more complex string, use:
$datetime = DateTime::createFromFormat("d M Y H:i:s", $your_string_here);
$timestamp = $datetime->getTimestamp();
Dênis Montone
Updated on July 21, 2022Comments
-
Dênis Montone almost 2 years
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?
-
NullUserException over 11 yearsYou should look into
DateTime::createFromFormat()
; example: codepad.viper-7.com/0b0edk. This allows you to set exactly the format you're expecting, saving you fromstrtotime()
's nonsensical parsing of American mm-dd style dates - an inhumanely stupid format if you think about it.
-
-
NullUserException over 11 yearsInitially, -1 for trying to get an extremely poor FGITW answer in. Downvote stays because it doesn't answer the question.
-
Naftali over 11 years@NullUserException sorry about that. I was in the process of typing and it submitted....
-
Sammitch over 11 yearsAll 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.