1
$date = "31/01/2017";
$date = date("Y-m-d", strtotime($date));

For some the above code is not working and giving me the result: $date = 1970-01-01;

When I am fetching date from database and converting in the same manner its working. But not working when i want to convert "d/m/Y" format to "Y-m-d"

I can convert the date in other ways by exploding, but why not the above code is working..??

Anup Surin
  • 38
  • 1
  • 10
  • You need to use either `m/d/y` with `/` or `d-m-y` with `-`. `strtotime()` expects it that way as `m/d/y` is a US format and `d-m-y` year is many other countries. – AbraCadaver May 17 '17 at 14:55
  • @AbraCadaver Sorry i could not get you.. – Anup Surin May 17 '17 at 14:58
  • You must use `01/31/2017` or `31-01-2017` or see the second answer on the duplicate. – AbraCadaver May 17 '17 at 14:59
  • 1
    Basically, when you use `strtotime`, you need to give it a string in one of [these formats that the parser understands](http://php.net/manual/en/datetime.formats.date.php), and "d/m/Y" isn't in that list. – Don't Panic May 17 '17 at 15:04
  • If you still want to use `strtotime` rather than `date_create_from_format` as in the duplicate answer, you can just `str_replace` the `/` in `$date` to `-` before using `strtotime`. – Don't Panic May 17 '17 at 15:07

1 Answers1

3

try like this

<?php
$date = "31-01-2017";
$date = date("Y-m-d", strtotime($date));
echo $date;
?>

Output:

2017-01-31

RaMeSh
  • 3,330
  • 2
  • 19
  • 31
  • your code is working, but why not the date format with "/" one.. The date format "2017-01-31" is getting converted to "31/01/2017" by using the same method.. – Anup Surin May 18 '17 at 13:31