2

I get an error trying to convert a string to DateTime, even though this has always worked before.

This is the procedure I used:

  1. Save a datetime to a text file like this:

    DateTime.Now.ToUniversalTime().ToString(); //results in something like this 20.9.2015 10.16.12
    
  2. 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);
John
  • 115
  • 3
  • 12
  • It works just fine for me ON Windows 10 targeting .net 4.6, anything special about your computer / locale (did you install another language when upgrading or anything that could relate to time formats?) – Ronan Thibaudau Sep 20 '15 at 10:38
  • Just to be clear, your second example works but the one with the date you gave doesn't work for me, so odds are you saved with one locale and then read it from the file with another locale, what does work for me is the Convert.ToDateTime(DateTime.Now.ToUniversalTime().ToString()) – Ronan Thibaudau Sep 20 '15 at 10:40
  • possible duplicate of [Converting a String to DateTime](http://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – Thomas Weller Sep 20 '15 at 10:43
  • I tried a few things and this seems to work correctly: string s = DateTime.Now.ToUniversalTime().ToString(); s = s.Substring(0, s.IndexOf(" ")).Replace('.', '/') + s.Substring(s.IndexOf(" ")).Replace('.', ':'); Convert.ToDateTime(s); But I have no idea why this would be necessary. The DateTime.Now.UniversalTime.ToString() gives the date in a format where dots (.) are used when the converter seemingly wants dashes (/) and colons (:) – John Sep 20 '15 at 10:46
  • Ronan Thibaudau I did also first believe that the error originated from that, but because the second example failed I changed my mind – John Sep 20 '15 at 11:01
  • What you get when you do DateTime.Now.ToUniversalTime().ToString()? – rkawano Sep 20 '15 at 11:17
  • You should define a specific format when saving your date and use the same format to convert it back, to avoid culture mismatches – Rubens Farias Sep 20 '15 at 11:35
  • **PSA:** `DateTime.Now.ToUniversalTime()` is just a slower version of `DateTime.UtcNow`. – Matt Johnson-Pint Sep 20 '15 at 18:40

3 Answers3

3

This probably does not work anymore due to your regional settings on control panel.

To avoid conflicts with regional settings on target enviroment, use DateTime.TryParseExact:

string s = streamReader.ReadLine(); //the saved string s = "20.09.2015 10.16.12"
DateTime d = DateTime.Now;
DateTime.TryParseExact(s, "dd.MM.yyyy HH.mm.ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);

Also, if this is your default format and you need this format for entire application, you can set the default culture on your config file.

This code:

Convert.ToDateTime(DateTime.Now.ToUniversalTime().ToString())

Should work on any enviroment, once that DateTime.ToString() and Convert.ToDateTime() without a format provider uses the same DateTimeFormatInfo, unless you are changing your culture between these calls. Note that DateTime.ToString() without format specifier will use General date/time pattern (G), that is based on current culture. And Convert.DateTime without FormatProvider will use current culture too (check these references on MSDN).

My last suggestion is, instead of doing replaces, you can do:

string s = DateTime.Now.ToUniversalTime().ToString("dd/MM/yyyy HH:mm:ss");
Community
  • 1
  • 1
rkawano
  • 2,443
  • 22
  • 22
  • This results in d = {1.1.0001 0.00.00} which is incorrect. The correct one would be d = {20.9.2015 10.48.48} – John Sep 20 '15 at 10:52
  • Make sure you are getting correct string on your file. And check your date format on Regional Settings (Control Panel \ Region \ Formats). – rkawano Sep 20 '15 at 11:01
  • My region format is English(Unites States), but this is not the issue. The issue is that I can not convert a string to DateTime even by using this line: DateTime d = Convert.ToDateTime(DateTime.Now.ToUniversalTime().ToString()); – John Sep 20 '15 at 11:08
1

I tried following code in console application, and it worked for me. And check .NETFiddle here

string s = "20.09.2015 10.16.12";
DateTime d;
bool isValid = DateTime.TryParseExact(s, "dd.MM.yyyy HH.mm.ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);

Try to understand how TryParseExact works. You can read about TryParseExact and formats here. It return a true if it successfully converts the value, else it returns a false.

Amnesh Goel
  • 2,617
  • 3
  • 28
  • 47
0

Please try with this.

CultureInfo objcul = new CultureInfo("en-GB");

DateTime.ParseExact(ValidFrom.Text,"dd/MM/yyyy", objcul);