I get an error trying to convert a string
to DateTime
, even though this has always worked before.
This is the procedure I used:
Save a datetime to a text file like this:
DateTime.Now.ToUniversalTime().ToString(); //results in something like this 20.9.2015 10.16.12
On application load up:
string s = streamReader.ReadLine(); //the saved string s = "20.09.2015 10.16.12" DateTime d = Convert.ToDateTime(s);
This results in this:
String was not recognized as a valid DateTime.
I have never experienced this problem before I installed Windows 10 and Visual Studio 2015, my previous setup was Windows 7 and Visual Studio 2013. The weird thing is that this also results in the same error:
DateTime d = Convert.ToDateTime(DateTime.Now.ToUniversalTime().ToString());
This did work perfectly in my previous setup, any ideas why it does not work any more?
Edit: I do believe that this question is not a duplicate of the question Converting a String to DateTime that Thomas Weller linked to. Because this problem is the result of changes in expected behaviour, see the second example. Also I did find a fix to this, but it is not practical:
string s = DateTime.Now.ToUniversalTime().ToString();
s = s.Substring(0, s.IndexOf(" ")).Replace('.', '/') + s.Substring(s.IndexOf(" ")).Replace('.', ':');
DateTime d = Convert.ToDateTime(s);