Thursday, September 16, 2010

Convert String to Date

To convert string to date You either specify a culture that uses that specific format :
like we want to convert string date "dd/MM/yyyy" to Date..

datetime mydate = Convert.ToDateTime(
txtdate.Text, CultureInfo.GetCulture("en-GB")
);

or use the ParseExact method:

datetime mydate = DateTime.ParseExact(
txtdate.Text, "dd/MM/yyyy", CultureInfo.Invariant
);

The ParseExact method only accepts that specific format, while the Convert.ToDateTime method still allows some variations on the format, and also accepts some other date formats.

To catch illegal input, you can use the TryParseExact method:

DateTime d;
if (DateTime.TryParseExact(txtdate.Text, "dd/MM/yyyy", CultureInfo.Invariant, DateTimeStyles.None, out d)) {
datetime mydate = d;
} else {
// communcate the failure to the user
}

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates