Convert dd/mm/yyyy to DateTime format
This resource explains as how to convert the dd/mm/yyyy dates to DateTime format. Many would have experienced the "String was not recognized as a valid DateTime" error. This is to overcome this error.
When you try to convert the Dates which are in dd/mm/yyyy format to DateTime , the Date will be recognised by default as mm/dd/yyyy format and you will get exception as "String was not recognized as a valid DateTime.". You will recognise this error only when your date is greater than 12 and if you give for eg:"14/04/2010" you will get the error. Once your date is greater than 12, since the system by default recognises it as month it will throw the exception.
To overcome this error , when your date is is "dd/mm/yyyy" format from database or from the UI then you can use the below code technique
System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
dateInfo.ShortDatePattern = "dd/MM/yyyy";
DateTime dt2 = Convert.ToDateTime("13.09.2011", dateInfo);
By following this you will not get the exception.
Also to compare two dates in c# in "dd/mm/yyyy" format you can try this
System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
dateInfo.ShortDatePattern = "dd/MM/yyyy";
DateTime dt1=Convert.ToDateTime("12.12.2010", dateInfo);
DateTime dt2 = Convert.ToDateTime("13.09.2011", dateInfo);
int result=DateTime.Compare(dt1, dt2);
string Daterelationship;
if (result < 0)
Daterelationship = "is earlier than";
else if (result == 0)
Daterelationship = "is the same time as";
else
Daterelationship = "is later than";
Though DateTime.ParseExact does the same the above method is efficient .
Hope this helps!!!
Regards,
S.Rajeswari
Application Engineer
Steadfast technologies
This was so simple, but I had to google like crazy for it. Thank you so much! Been stuck on this for hours.