0

I am working on getting the date validated before we insert them in to the mySQl server. Below is what I am trying

   DateTime startDate = new DateTime(2009, 12, 31);
   var currentTime = DateTime.Now;
   DateTime endDate = currentTime.Date;

   DateTime DOB = DateTime.ParseExact(emp[i].DateOfBirth, "yyyy-MM-dd HH:mm:ss,fff",                         System.Globalization.CultureInfo.InvariantCulture);

   if (!(DOB.Date > startDate && DOB.Date <= endDate))
   {
       WriteValidationFailure("Failed - DOB is Invalid");
   }

Here emp[i].DateOfBirth is a string and hold the value like 01/01/2009. When I run the application it throws enter image description here

user4912134
  • 1,003
  • 5
  • 18
  • 47
  • 1
    Your format expression does not match to your input data. – Uladzimir Palekh Mar 09 '17 at 18:00
  • Try DateTime.Parse only with the datetime value, no format – NicoRiff Mar 09 '17 at 18:00
  • Possible duplicate of [Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"](http://stackoverflow.com/questions/1368636/why-cant-datetime-parseexact-parse-9-1-2009-using-m-d-yyyy) – maraaaaaaaa Mar 09 '17 at 18:06
  • Why don't you use **epoch time** to save into database :) – HoangHieu Mar 09 '17 at 18:07
  • @HoangHieu, this question not about storing date in the DB, it's about wrong parsing before storing. Also epoch is not good choice if you need just write and read data to/from DB. Native date types is better choice for this case as does not require any conversions. – Uladzimir Palekh Mar 09 '17 at 18:12

1 Answers1

0

You need to use one of these statements to parse your date:

DateTime DOB = DateTime.ParseExact(emp[i].DateOfBirth, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);

or

DateTime DOB = DateTime.ParseExact(emp[i].DateOfBirth, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

First if your dates contains month as first part and second for days as first part.

Uladzimir Palekh
  • 1,846
  • 13
  • 16