views:

54

answers:

5

Hi,

I have 2 DateTime objects, which I save to a file after using the ToShortDateString() function; the strings look like "12/15/2009". I am stuck on this part now, I want to initialize DateTimeObject(s) with these strings so I can compare the timespan between the date dates. Any help appreciated.

A: 

Did you try DateTime.Parse(str)?

Myles
From my experience, this may not work in this case as the format provided is dd/MM/yyyy and will probably get a string is not recognised as a valid datetime. DateTime.Parse(str) works for strings in the format yyyy/MM/dd
Kamal
A: 

Extract year, month and day, and than use smth like:

var dt = new DateTime(Year,Month,Day)

or crete an extension method to convert back to dateTime this kind of strings, but in general the body of that extension methad would be smth like this.

diadiora
+4  A: 

You can try

DateTime date = DateTime.ParseExact("12/15/2009", "MM/dd/yyyy", null);

Have a look at

astander
Thank you, just what I wanted!
IaskQuestions
+2  A: 

Hi,

Assuming you're reading back the dates from the file in string format

string date1 = "28/12/2009"; //this will be from your file
string date2 = "29/12/2009"; //this will be from your file
DateTime d1 = DateTime.ParseExact(date1,"dd/MM/yyyy", null);
DateTime d2 = DateTime.ParseExact(date2, "dd/MM/yyyy", null);
TimeSpan t1 = d2.Subtract(d1);
Kamal
+1  A: 

I usually try to stick to this when dealing with DateTime/string transitions:

  • When persisting dates in a text format, format it explicitly. Preferably to a standardized format (such as ISO 8601).
  • When reading the date back, parse it to a DateTime object using the same, explicitly defined format.

This way your code will not fail when used in places where the date format differs from yours, or if the file is created on one locale, and then parsed in another.

private static string DateToString(DateTime input)
{
    return input.ToString("yyyy-MM-dd");
}

private static DateTime StringToDate(string input)
{
    return DateTime.ParseExact(input, "yyyy-MM-dd", CultureInfo.InvariantCulture);
}
Fredrik Mörk