0

I want to convert php date from Y-F-d format to Y-m-d format. I use the code below.

<?php
$originalDate = "2014-March-03";
$newDate = date("Y-m-d", strtotime($originalDate));
echo $newDate ;
?>

I get an output like

2014-03-01

When i convert the date "2014-Mar-03"

<?php
$originalDate = "2014-Mar-03";
$newDate = date("Y-m-d", strtotime($originalDate));
echo $newDate ;
?>

I get ouput like

2014-03-03

Why the first one does not give the correct result?

Nandu
  • 3,076
  • 8
  • 34
  • 51

3 Answers3

6

Simply use DateTime class,

$date = DateTime::createFromFormat('Y-M-d', '2014-Mar-03');
echo $date->format('Y-m-d');

$date = DateTime::createFromFormat('Y-F-d', '2014-March-03');
echo $date->format('Y-m-d');

DEMO.

Reason: As strtotime only accept date in specific format (ISO 8601 (YYYY-MM-DD)), It want be able to recognize all formats of date we provide to it. Read Note section of strtotime function for more details.

Whereas DateTime::createFromFormat function returns new DateTime object formatted according to the specified format and than we can use that object to convert in any format of date.

Rikesh
  • 26,156
  • 14
  • 79
  • 87
  • i agree with your answer but why date() is not working? – Rakesh Sharma Jul 02 '14 at 06:11
  • Because strtotime only accept date in specific format. It want be able to recognize all formats of date you provide to it. [Read Note](http://in3.php.net/manual/en/function.strtotime.php#refsect1-function.strtotime-notes) section of strtotime function. – Rikesh Jul 02 '14 at 06:14
  • i think you need to add this in your answer – Rakesh Sharma Jul 02 '14 at 06:16
0

You need to use F instead of M in date function

$originalDate = "2014-Mar-03";
$newDate = date("Y-F-d", strtotime($originalDate));
echo $newDate ;

F is for full textual representation of a month, such as January or March.

Moeed Farooqui
  • 3,604
  • 1
  • 18
  • 23
0

You can use:

$originalDate = "2014-March-03";
$date = DateTime::createFromFormat('Y-F-d', $originalDate);
echo $date->format('Y-m-d');

Output is:

2014-03-03
The K
  • 59
  • 7