Convert String to DateTime using ASP.NET
I saw the question repeatedly asking on forums ie: how to convert the String to datetime.
even if someone give solution still the problems exists..,
Error: String is not recognized as a valid DateTime.
Here i am giving the solution to overcome the problem.
First make sure whether you entered is a valid date or not because User may enter alphabets, special symbols etc.. so in order to avoid that , I have to validate the textbox. Here i am using the Regex to to validate the date.
This is my Article to vaildate date using Regex
try { string sDate ="06/05/2010"; // this the regex to match the date ie: dd/MM/yyyy string _dateExpression = @"^((0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](?:19|20)\d\d)$"; Regex chkDate = new Regex(_dateExpression); if ((chkDate.IsMatch(sDate)) { // so if the date is valid and its matched you can store the date on DB or do some manipulatio. } else { // show invalid date } } catch (System.FormatException ex) { // show invalid date } catch(Exception ex1) { throw; }
So if the user enter other than numbers it shows format exception to avoid this exception. once i caught the FormatException i am showing the Message to user ie:- input is not valid date or something.
Another small manipulation on DateTime
DateTime sDate = new DateTime(); sDate = DateTime.Today; // Here i am getting like this 5/6/2010 // So i want this format 05/06/2010 - for this i am using Format to Convert the Date as i Want. string gDate = String.Format("{0:dd-MM-yyyy}", sDate);
Thanks to All.
Read more »