Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Y-m-d H:i:s to Y-m-d in PHP? [duplicate]

Tags:

date

php

time

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.

like image 304
qwentinnau Avatar asked Aug 10 '11 18:08

qwentinnau


People also ask

How convert date from yyyy-mm-dd to dd mm yyyy format in PHP?

Change YYYY-MM-DD to DD-MM-YYYY In the below example, we have date 2019-09-15 in YYYY-MM-DD format, and we will convert this to 15-09-2019 in DD-MM-YYYY format. $orgDate = "2019-09-15"; $newDate = date("d-m-Y", strtotime($orgDate)); echo "New date format is: ".

How can I get current date in YYYY-MM-DD format in PHP?

date_default_timezone_set('UTC'); echo "<strong>Display current date dd/mm/yyyy format </strong>". "<br />"; echo date("d/m/Y"). "<br />"; echo "<strong>Display current date mm/dd/yyyy format</strong> "."<br />"; echo date("m/d/Y")."<br />"; echo "<strong>Display current date mm-dd-yyyy format </strong>".

How to Convert date format in PHP?

c - The ISO-8601 date (e.g. 2013-05-05T16:34:42+00:00) r - The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200) U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

What does Strtotime mean in PHP?

Definition and Usage The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.


2 Answers

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');
like image 97
Marc B Avatar answered Sep 22 '22 23:09

Marc B


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
like image 25
Michael Berkowski Avatar answered Sep 21 '22 23:09

Michael Berkowski