I've some some php that changes the format of the time retrieved from the database:
$selectedDate = $_GET['date'];
$formatedDate = date("Y-d-m",strtotime($selectedDate)); // Y-m-d outputs Y-d-m oddly
echo "<form name='selectedDate' action='info.php' method='GET'>";
echo "<select name='date' onchange='this.form.submit()'>";
echo "<option value=select>Select a Date</option>";
while ($row = mysql_fetch_array($result))
{
$date = date("m-d-Y",strtotime($row['date']));
echo "<option>" . $date . "</option>";
}
echo "</select>";echo "<br />";
echo $selectedDate; // 1.) in: 02-13-2013, 2.) in: 02-12-2013
echo "<br />";
echo $formatedDate; // 1.) out: 1970-01-01, 2.) out: 2013-02-12
echo "<br />";
echo date("Y-m-d");
echo "<noscript>";
echo "<input type='submit' value='Select'>";
echo "</noscript>";
echo "</form>";
Now, for $formatedDate
, as stated, if I use Y-m-d
for output, I get 2013-12-02
instead of 2013-02-12
. Not to mention that even though all $selectedDate
's are in m-d-Y
before being formatted, it doesn't recognize them as dates
. I have the feeling that it's something totally silly that I'm missing, but I just can't see it.
So my question is, why does the strtotime()
reverse my month and days, and why does it not recognize all dates? Is there a better way of getting this done?
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.
Please use following way
$date = DateTime::createFromFormat('m-d-Y', '02-14-2013'); echo $date->format('Y-m-d');
Per http://www.php.net/manual/en/datetime.formats.php and the list at: http://www.php.net/manual/en/datetime.formats.date.php
The 'm-d-Y' format is not recognised by strtotime().
It's being interpreted as originally being in 'd-m-Y' format. The '02-13-2013' is interpreted as '2nd of 13th Month 2013' which is invalid hence the unix epoch is output.
You could try replacing the '-' with slash and then it will match format 1 (m/d/Y)