How to convert Y-m-d H:i:s to Y-m-d in PHP? [duplicate]
How to convert Y-m-d H:i:s to Y-m-d in PHP?
I have e.g.
$date = "2011-08-10 20:40:12";
and would like to convert it to just
$output = "2011-08-10";
Thanks in advance.
quick/dirty:
$output = substr('2011-08-10 20:40:12', 0, 10);
slightly more robust:
$output = date('Y-m-d', strtotime('2011-08-10 20:40:12'));
fairly reliable:
$output = DateTime::createFromFormat('Y-m-d h:i:s', '2011-08-10-20:40:12')->format('Y-m-d');
Easily done with strtotime()
, and capable of changing to any other date format you may need as well.
$old_date = "2011-08-10 20:40:12";
$new_date = date("Y-m-d", strtotime($old_date));
echo $new_date;
// Prints 2011-08-10
Well, a simple way to do it would be the following (if you've already gotten the date in a string):
$output = substr($date, 0, 10);
This would mean that you grab the first 10 characters in "2011-08-10 20:40:12", leaving you with "2011-08-10"!
You can use the built in php date format function:
http://php.net/manual/en/datetime.format.php
to do this:
$date = date_format($date, 'Y-m-d');
Another solution, thought not as good is to simply do a substring:
$newDate = substr($date, 0, 10)
$date = date("Y-m-d", strtotime($date));
Just use the date format for date only and convert your string to a timestamp.
I prefer strftime
to date since it's format input matches those in C and other languages.
$output = strftime( '%Y-%m-%d', strtotime( $date) );
$old_date = "2011-08-10 20:40:12";
$new_date = date("Y-m-d", strtotime($old_date));
echo $new_date;
// Prints 2011-08-10
This should be very useful.
A tweak to the method using explode so you can turn it into a one liner:
list($date) = explode(' ', $date);
the list function is very handy for dates.
Another example using list:
list($year, $month, $day) = explode(' ', $date);
Also, you are best to use ' instead of " in strings, unless your string includes variables.
e.g.
- 'yada'
- 'bing'
- "Hello {$bob}"
I'm fed up seeing even the PHP docs use "string" in examples where they should use 'string' :o)
Try:
$date = explode(" ",$date);
$output = $date[0];
If they are separated by space, you can use explode to separate them.
精彩评论