If the format of date input variable is fixed and certain, it’s possible to use the explode() function to split the day, month and year components. For example,
$date = "07/08/2015"; $date = explode('/', $date);
If your date is using different separator, change the value according in the explode() function, i.e. – (dash) instead of / (slash). Explode() function returns an array containing the individual date elements. You can access the individual day, month and year values by accessing directly the elements of array, or assign them to variables. For example (assuming date format is MM/DD/YYYY):
$month = $date[0]; $day = $date[1]; $year = $date[2];
The preg_match() function is also able to perform the similar splitting of date. The following example assuming all date has 2 day digits, 2 month digits, and 4 year digits in MM/DD/YYYY format.
preg_match('#^(\d{2})-(\d{2})-(\d{4})$#', $date, $results)); $month = $results[1]; $day = $results[2]; $year = $results[3];
If you are uncertain about the input format, or the input date value is in various standard English textual format or long date format, use the strtotime() function to convert the string to proper date format, before retrieving the date() function to return the proper day, month and year components of the date. For example:
$date = strtotime($input); $day = date('d',$date); $month = date('m',$date); $year = date('Y',$date);
If the separator is a slash (/), then it’s the American m/d/y.
If the separator is a dash (-) or a dot (.), then it’s the European d-m-y.
If the separator is a dash (-) and year is given in a two digit format, the date string is parsed as y-m-d.
If strtotime() confuse you, another alternative is by using date_parse_from_format(), which able to get info about given date formatted according to the specified format. For example:
$date = '07/08/2015'; $dateArray = date_parse_from_format('m/d/Y', $date);
The result is an array:
Array
(
[year] => 2015
[month] => 7
[day] => 8
[hour] => 13
[minute] =>
[second] =>
[fraction] =>
[warning_count] => 0
[warnings] => Array
(
)
[error_count] => 0
[errors] => Array
(
)
[is_localtime] => 0
[zone_type] => 0
[zone] => 0
[is_dst] =>
)