Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to Date and DateTime

If I have a PHP string in the format of mm-dd-YYYY (for example, 10-16-2003), how do I properly convert that to a Date and then a DateTime in the format of YYYY-mm-dd? The only reason I ask for both Date and DateTime is because I need one in one spot, and the other in a different spot.

like image 768
Chris Pinski Avatar asked Jun 04 '11 19:06

Chris Pinski


People also ask

Can we convert string to date in SQL?

In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.

How do I convert a string to a timestamp in Python?

Import the datetime library. Use the datetime. datetime class to handle date and time combinations. Use the strptime method to convert a string datetime to a object datetime.


2 Answers

Use strtotime() on your first date then date('Y-m-d') to convert it back:

$time = strtotime('10/16/2003');  $newformat = date('Y-m-d',$time);  echo $newformat; // 2003-10-16 

Make note that there is a difference between using forward slash / and hyphen - in the strtotime() function. To quote from php.net:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

like image 130
Ibu Avatar answered Sep 17 '22 01:09

Ibu


You need to be careful with m/d/Y and m-d-Y formats. PHP considers / to mean m/d/Y and - to mean d-m-Y. I would explicitly describe the input format in this case:

$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d'); 

That way you are not at the whims of a certain interpretation.

like image 30
Matthew Avatar answered Sep 21 '22 01:09

Matthew