0

I find a problem related to the date function in php

i want to convert a date '04-08-2016'(mm-dd-yyyy) into a different format '2016-04-08'(yyyy-mm-dd). But it produces the result as '2016-08-04'(yyyy-dd-mm) instead of '2016-04-08'(yyyy-mm-dd).

my code is

     $date = '04-08-2016';
     echo date('Y-m-d',strtotime($date));

If i place '/' in place of '-' then it is working fine.

Can anyone tell me why this is happening?

11
  • Whithout your code, it is hard to see why, you know... Commented Apr 8, 2016 at 13:30
  • I am just converting into mysql format date(yyyy-mm-dd). For your reference you can take a variable $date = '04-08-2016'';echo date('Y-m-d',strtotime($date)); Commented Apr 8, 2016 at 13:31
  • show your code, don't describe what you do. If it does not have the expected result, you're doing something wrong... Commented Apr 8, 2016 at 13:32
  • 1
    And if you used DateTime objects, PHP provides a helpful createFromformat() method that allows you to tell PHP what format is being used for a date, eliminating any ambiguity or guessing Commented Apr 8, 2016 at 13:34
  • 1
    @AzharAhmad - read the page that I linked and it will tell you how PHP differentiates between dd-mm-yyyy and mm-dd-yyyy using the separator "/" or "-".... there is nothing wrong with strtotime(), just with your lack of knowledge, and that lack willl be eliminated if you read the PHP docs link Commented Apr 8, 2016 at 13:51

2 Answers 2

2

You can use the DateTime object:

$date = '04-08-2016';
$d = DateTime::createFromFormat("m-d-Y", $date);
echo $d->format("Y-m-d");

The reason you need to do this is date conventions. As specified in http://php.net/manual/en/function.strtotime.php

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. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d.

Sign up to request clarification or add additional context in comments.

1 Comment

You have forget to provide string in createFromFormat("m-d-Y"). It should be $d = DateTime::createFromFormat("m-d-Y", $date);
1

Try this:

$date = '04-08-2016';
$timeArray = strptime($date, '%m-%d-%Y');
$timestamp = mktime(0, 0, 0, $timeArray['tm_mon']+1, $timeArray['tm_mday'], $timeArray['tm_year']+1900);
echo date('Y-m-d', $timestamp);

This allows you to specify the format yourself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.