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 DateTime object(s) with these strings so I can compare the timespan between the date dates. Any help appreciated.
We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.
Strptime() The strptime() method takes the date as an input and converts it into a date object.
Import the datetime library. Use the datetime. datetime class to handle date and time combinations. Use the strptime method to convert a string datetime to a object datetime.
You can try
DateTime date = DateTime.ParseExact("12/15/2009", "MM/dd/yyyy", null);
Have a look at
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With