pete the pagan-gerbil
pete the pagan-gerbil

Reputation: 3166

Different results from new DateTime() and DateTime.Parse

I noticed some odd behaviour in a unit test for C#.

Given the following code:

var dateTime = DateTime.Parse("01/01/2015");
Assert.AreEqual(dateTime, new DateTime(2015, 1, 1));

I get a failed test with the result:

Expected: 2015-01-01 00:00:00.000
But was:  01/01/2015 00:00:00 +00:00

I've tried calling ToString() on both, passing in CultureInfo.CurrentCulture and setting the DateKind on the new DateTime call to both Local and UTC but I get the same sort of results.

Why don't these two methods give the same result?

Upvotes: 8

Views: 566

Answers (3)

pete the pagan-gerbil
pete the pagan-gerbil

Reputation: 3166

The question assumes in the simplified example that the first variable is a DateTime, when it is actually a DateTimeOffset. The public methods consumed that generated that variable had changed, and I presumed incorrectly that the return type was still a DateTime.

So the reason that they give different results is because they are different!

Lesson One: Check types even when you know what they are. Lesson Two: Don't simplify too much in SO question examples.

Upvotes: 0

MistyK
MistyK

Reputation: 6222

You should never ever hardcode dates as string. What is the point of doing it?

DateTime.Parse("01/01/2015")

instead do this:

new DateTime(2015,1,1)

DateTime.Parse is using your current culture by default to create a date. Consider following example:

DateTime.Parse("09/06/2015");

Is it 9th June or 6th September? Depending on your machine culture you will get different results. If your DateTime string comes from somewhere then you can force Parse method to use particular Format/Culture.

Going back to the question it's probably culture dependent.

Upvotes: 0

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

I would give a shot with:

Assert.IsTrue(DateTime.Compare(DateTime.Parse("01/01/2015"), new DateTime(2015, 1, 1) == 0); 

Upvotes: 1

Related Questions