0

How to validate specific date ? For example user types 29-12-2005. Of course I can validate it with regular expression etc.. But 2005 year had not 29 days in February. Any date functions and methods did not help me.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Mikael
  • 1,209
  • 1
  • 16
  • 47
  • 2
    Before posting a question, you should have done the proper research and made attempts to solve your issue yourself. Then, if you get stuck on something _specific_, come back and show us your attempt. Please read [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) and also [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) – M. Eriksson Oct 11 '18 at 18:27
  • 4
    Possible duplicate of [php date validation](https://stackoverflow.com/questions/12030810/php-date-validation) – Nigel Ren Oct 11 '18 at 18:29

2 Answers2

1

You can use Last day of this month

For example

echo (new DateTime('1-12-2005'))->modify('Last day of this month')->format('d');

Output:

31

Sandbox

Note this is for Dec (12). If you do it for 1-2-2005 it's 28, you don't want to necessarily use 29, because DateTime will kick it into the next month, which brings us to this one.

Simply check the date (it should be the same if its a valid day):

$date = '29-2-2005';

echo (new DateTime($date))->format('d-m-Y') == $date  ? 'true' : 'false';

Output:

false //ex. 1-3-2005 == 29-2-2005 is false

And then of course there is this way:

$date = explode('-','29-2-2005');

var_dump(checkdate( $date[1], $date[0], $date[2] ));

Also false, but the disadvantage of checkdate is you need to know the format of the date ahead of time. Using DateTime, it will accept multiple formats without issues.

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
0

There is simple function in PHP to check number of days in a month for a given year:

cal_days_in_month(CAL_GREGORIAN, 2, 2005); // 28