tags:

views:

174

answers:

3

I've been using the DateTime class in PHP because date() has the downsides of Unix Timestamp. However, neither approach detects invalid dates for months which don't have 31 days but attempt to use the 31st day.

Example Code:

try {
$date = new DateTime('02/31/2018');
$formattedDate = $date->format('Y-m-d');
} catch (Exception $e) {}
echo $formattedDate;

Example Output:

2018-03-03

Update 1: To use checkdate() I need the component parts of the date. To get that, I will need to instantiate a DateTime object with the date string as the constructor. In the case of '02/31/2018', it will convert it to '03/03/2018' when instantiated. At that point it will be too late to run the component month, day, year through checkdate(). What is the solution?

Update 2: Getting the component part of the dates is easy if I force a specific format (e.g. mm/dd/yyyy), but if I accept all formats accepted by strtotime(), I cannot perform a checkdate before running it through strtotime() -> date() or DateTime::__construct -> DateTime::format().

+6  A: 

Try the checkdate function.

Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.

Parameters

month

The month is between 1 and 12 inclusive.

day

The day is within the allowed number of days for the given month . Leap years are taken into consideration.

year

The year is between 1 and 32767 inclusive.

Andrew Hare
+2  A: 

Extend DateTime and re-implement the default constructor to use checkdate. Bit easier to do that once and replace all DateTime( with MyDateTime( so you can add more checks as you go along. e.g. Year > 1940...

Just Jules
A: 

To get the component parts of the date, you can just split the string...

$date = explode('/','02/18/2018');

Then use checkdate(), now that you have the components.

Matchu