Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check given date exist in month or not?

Tags:

date

c#

linq

I have a combo Box In which I made a collection of dates from 1 to 31 and also I have a checklist box in which I made a collection of month from Jan to Dec.
Now I have to put validation on date that if user select 31 and select month Jan, Feb, Mar then a message popup and inform them 31 does not exist in February

enter image description here

like image 743
Coderz Avatar asked Jan 03 '14 09:01

Coderz


People also ask

How can I check the validity of a date?

Given date in format date, month and year in integer. The task is to find whether the date is possible on not. Valid date should range from 1/1/1800 – 31/12/9999 the dates beyond these are invalid. These dates would not only contains range of year but also all the constraints related to a calendar date.

How do you check date is this month in PHP?

PHP checkdate() Functionvar_dump(checkdate(12,31,-400));

How do you check that date is in same month in JavaScript?

JavaScript Date getMonth() getMonth() returns the month (0 to 11) of a date.


1 Answers

You want the DateTime.DaysInMonth method:

public bool IsDateValid(int year, int month, int day) {
    return day <= DateTime.DaysInMonth(year, month);
}

I'm assuming that the year and month values will always be sensible, and that day will always be greater than or equal to 1. You could easily add argument validation. I'm also assuming that you already have the month as a number, rather than just a name. (Differentiate between the display format of a value and the underlying value.)

Note that you'll need a year picker, otherwise you won't know whether February 29th is valid or not.

(And as Mitch says, it would be better to design a UI where invalid choices simply don't appear, ideally.)

like image 148
Jon Skeet Avatar answered Sep 22 '22 12:09

Jon Skeet