What causes this behavior in our C # DateTime?

[Test]
public void Sadness()
{
   var dateTime = DateTime.UtcNow;
   Assert.That(dateTime, Is.EqualTo(DateTime.Parse(dateTime.ToString())));
}

Failure:

 Expected: 2011-10-31 06:12:44.000
 But was:  2011-10-31 06:12:44.350

I want to know what happens behind the scenes in ToString (), etc., to trigger this behavior.

EDIT After watching Jon's answer:

[Test]
public void NewSadness()
{
    var dateTime = DateTime.UtcNow;
    Assert.That(dateTime, Is.EqualTo(DateTime.Parse(dateTime.ToString("o"))));
}

Result:

Expected: 2011-10-31 12:03:04.161
But was:  2011-10-31 06:33:04.161

The same result with capital and a little "o". I am reading documents, but still unclear.

+5
source share
2 answers

The default format specifier is "G" - a general-purpose format that has limited precision. If you want to reproduce exactly the same, use the roundtrip specifier, "O".

string s = dateTime.ToString("O", CultureInfo.InvariantCulture);
Assert.That(dateTime, Is.EqualTo(DateTime.ParseExact(
       s, "O", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind)));
+6
source

, dateTime.ToString() - , , , . ToString() , , ...

"o" , . , - :

2011-10-31T06:28:34.6425574Z

EDIT: , :

string text = dateTime.ToString("o");
// Culture is irrelevant when using the "o" specifier
DateTime parsed = DateTime.ParseExact(text, "o", null,
                                      DateTimeStyles.RoundtripKind);
+9

All Articles