Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is causing this behavior, in our C# DateTime type?

Tags:

c#

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

Failed :

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

I wish to know what is happening behind the scenes in ToString() etc to cause this behavior.

EDIT After seeing 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

Same result with capital and small 'o' . I'm reading up the docs, but still unclear.

like image 921
Zasz Avatar asked Oct 31 '11 06:10

Zasz


People also ask

What is the main cause of our behavior?

Behavior is driven by genetic and environmental factors that affect an individual. Behavior is also driven, in part, by thoughts and feelings, which provide insight into individual psyche, revealing such things as attitudes and values.

What are the causes in the change in human behavior?

They propose three key factors that influence behavior change: Information about the behavior. Motivation to perform the behavior. Behavioral skills to perform the behavior.

What are the causes of social behavior?

The social psychology seeks to understand the causes of human social behaviour. These causes are characteristics and actions of others, cognitive processes, environmental variables, culture, and biological causes.

Why is human behavior important to our society?

Strongly rooted in psychology and sociology, studies of human behavior give us an academic understanding of motivations, productivity, and how teams work. In turn, these insights can help make workplaces or any group setting more productive.


1 Answers

Have a look at what dateTime.ToString() produces - it will typically only be accurate to the second, although it depends on cultural settings. If ToString() only gives a result accurate to a second, there's no way that parsing the string can give more information...

You can use the "o" standard format string to provide a round-trippable string representation. For example, at the moment it produces something like:

2011-10-31T06:28:34.6425574Z

EDIT: You need to parse with the same specifier to get the same result back:

string text = dateTime.ToString("o");
// Culture is irrelevant when using the "o" specifier
DateTime parsed = DateTime.ParseExact(text, "o", null,
                                      DateTimeStyles.RoundtripKind);
like image 152
Jon Skeet Avatar answered Sep 26 '22 14:09

Jon Skeet