Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate DateTime format?

Tags:

I am suppose to let the user enter a DateTime format, but I need to validate it to check if it is acceptable. The user might enter "yyyy-MM-dd" and it would be fine, but they can also enter "MM/yyyyMM/ddd" or any other combination. Is there a way to validate this?

like image 291
Kevin Cho Avatar asked Jul 27 '12 21:07

Kevin Cho


People also ask

How do I check if a date is valid?

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 validate a date in YYYY MM DD format in Java?

Validate Using DateFormat Next, let's write the unit test for this class: DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019"));


1 Answers

Are you looking for something like this?

DateTime expectedDate; if (!DateTime.TryParse("07/27/2012", out expectedDate)) {     Console.Write("Luke I am not your datetime.... NOOO!!!!!!!!!!!!!!"); } 

If your user knows the exact format(s) needed...

string[] formats = { "MM/dd/yyyy", "M/d/yyyy", "M/dd/yyyy", "MM/d/yyyy" }; DateTime expectedDate; if (!DateTime.TryParseExact("07/27/2012", formats, new CultureInfo("en-US"),                              DateTimeStyles.None, out expectedDate)) {     Console.Write("Thank you Mario, but the DateTime is in another format."); } 
like image 187
Hans Z Avatar answered Oct 04 '22 03:10

Hans Z