Donotalo
Donotalo

Reputation: 13025

How to parse string to DateTime following PC regional setting

The following code:

string s = DateTime.Now.ToString();
DateTime dt;
DateTime.TryParse(s, out dt);

textBox1.AppendText(s + "\n");
textBox1.AppendText(DateTime.Now + "\n");
textBox1.AppendText(dt.ToString() + "\n");

DateTime.TryParse(s,
                  CultureInfo.CurrentCulture.DateTimeFormat,
                  DateTimeStyles.None,
                  out dt);
textBox1.AppendText(dt.ToString() + "\n");

produces the following output on the textbox:

13.09.2013 1602.38
13.09.2013 1602.38
01.01.0001 0000.00
01.01.0001 0000.00

Why TryParse can't parse the string s to correct DateTime object? I want my program to be able to correctly parse the strings formatted like s. How can I do that?

This is a C# WPF program running on .NET Framework 4.

Upvotes: 3

Views: 3485

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73482

It appears your DateSeperator and TimeSeperator are same. In this case it is .

While converting DateTime to string framework just places . in place of those seperators so converting to string works smooth.

But when parsing it back to DateTime when datetime parser finds . character It doesn't have any clue in finding whether the element is Date part or Time part. and hence it fails.

Here is the snippet reproducing the issue and shows the fix.

        CultureInfo c = new CultureInfo("en-us", true);
        c.DateTimeFormat.DateSeparator = ".";
        //c.DateTimeFormat.TimeSeparator= ".";//this will fail
        c.DateTimeFormat.TimeSeparator= ":";//this will work since TimeSeparator and DateSeparator  are different.
        Thread.CurrentThread.CurrentCulture = c;

        string s = DateTime.Now.ToString();
        DateTime dt;
        DateTime.TryParse(s, out dt);

        Console.WriteLine(s + "\n");
        Console.WriteLine(DateTime.Now + "\n");
        Console.WriteLine(dt.ToString() + "\n");

        DateTime.TryParse(s,
                          CultureInfo.CurrentCulture.DateTimeFormat,
                          DateTimeStyles.None,
                          out dt);
        Console.WriteLine(dt.ToString() + "\n");

Conclusion: You should not set DateTimeFormat and TimeSeparator to the same value. Doing so gives trouble for the runtime in parsing DateTime so it fails. :)

Upvotes: 3

Related Questions