Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different results from new DateTime() and DateTime.Parse

Tags:

c#

datetime

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?

like image 603
pete the pagan-gerbil Avatar asked Sep 24 '15 08:09

pete the pagan-gerbil


People also ask

What does DateTime parse return?

The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

How does DateTime parse work?

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.

What's wrong with a line like this DateTime parse Mystring?

Because the Parse(String) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results.

How to use DateTime parse in c#?

TryParse() always try to parse the string value datetime. If conversion succeeded then it returns correct DateTime value and MinValue(1/1/0001 12:00:00 AM) if conversion failed. If string value is null or empty and you are trying to convert it DateTime then it returns MinValue only.


1 Answers

I would give a shot with:

Assert.IsTrue(DateTime.Compare(DateTime.Parse("01/01/2015"), new DateTime(2015, 1, 1) == 0); 
like image 93
Thomas Ayoub Avatar answered Sep 23 '22 11:09

Thomas Ayoub