views:

73

answers:

5

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.

+2  A: 

Use d.ToString("MM/dd/yyyy")

For more options check out http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx

Edit: Read it wrong

Use DateTime.Parse() to parse the string to a datetime. http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

You can also use DateTime.TryParse to see if the string is able to convert to a date first. http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx

Alternatively you can also use Convert.ToDateTime()

Gage
+1  A: 

If you want the DateTime variable back after sending it to a string, save yourself the trouble and just cache or pass the actual DateTime variable around scopes to wherever you need it later and don't bother converting the text back into a DateTime class..

Sorry I just realized this doesn't answer your request, so what you're looking for is:

DateTime.ParseExact(someDateTime, "the format string you used to .tostring generating the string", null);
Jimmy Hoffa
+7  A: 

The reverse of DateTime.ToString("yyyyMMdd") is DateTime.TryParseExact, passing "yyyyMMdd" as a format string.

IFormatProvider is 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 preferences
  • Or CultureInfo.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
Tim Robinson
examples:http://msdn.microsoft.com/en-us/library/ms131044.aspx
Zippit
+1  A: 

Convert.ToDateTime("07/30/2010");

Kevin
+1  A: 

I'm assuming you mean to convert a string to a DateTime format. If so use this:

    DateTime yourStringConverted = Convert.ToDateTime( yourString );
Joseph Stein