I have a string I need to convert back to a date. I can call .ToString(“yyyyMMdd”) and get the string i want. My question is how can I convert that back into a date? I’m trying something like the following with no luck.
DateTime d;
var formatInfo = new DateTimeFormatInfo {ShortDatePattern = "yyyyMMdd"};
if (DateTime.TryParse(details.DetectionTime.Date, formatInfo, DateTimeStyles.None, out d))
{
lit.Text = d.ToShortTimeString(); //would like 07/30/2010 as the text
}
I’ve never used DateTimeFormatInfo before if that isn’t obvious. Can someone point me in the right direction. I know I could probably use substring and create a new DateTime(y, m, d) etc… I’m just wondering since c# interpreted .ToString() correctly, if it can’t derive a date from the very same string it output.
The reverse of
DateTime.ToString("yyyyMMdd")isDateTime.TryParseExact, passing"yyyyMMdd"as a format string.IFormatProvideris a bit of a red herring. You’ll normally pass either :Thread.CurrentThread.Culture, if you’re parsing a date typed by the user, when you should obey the user’s date preferencesCultureInfo.InvariantCulture, if you’re parsing a date provided by a program, when your behaviour shouldn’t depend on the preferences the user has set up