Reputation: 489
I've got the following code that I am using to extract the day into a $day variable. However, PHP seems to be using the default config date format and is assuming the date format as d-m-Y. Here is my code:
$dateformat = "m-d-Y";
$selected_date = "04-30-2013";
$day = date(d, strtotime($selected_date));
echo $day;
Is there a way for me to dynamically make PHP execute based on the format defined in the $dateformat variable?
Thanks
Upvotes: 0
Views: 154
Reputation: 76666
The problem here is that strtotime()
cannot parse date strings in custom formats. From the documentation for strtotime()
(emphasis mine):
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.
The solution is to use DateTime::createFromFormat()
. It can parse a date with custom format:
$dateObj = DateTime::createFromFormat($dateformat, $selected_date);
$day = $dateObj->format('d'); // => 30
Upvotes: 2