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?
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).
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.
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.
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.
I would give a shot with:
Assert.IsTrue(DateTime.Compare(DateTime.Parse("01/01/2015"), new DateTime(2015, 1, 1) == 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With