ak1
ak1

Reputation: 379

Assert.Equal is not working with dates

I have written a simple test method to verify a method that converts a long value to DateTime, following is the code...

        [TestMethod]
    public void ConvertToDateTime_TestMethod()
    {
        long date = 1500024370374;

        DateTime result = date.GetDateTime(); 
        DateTime comparisonDate = new DateTime(2017, 07, 14, 9, 26, 10);
        Assert.AreEqual(result, comparisonDate);
    }

Point is that both date and time values are exactly same (also verified in watch window) why does it gives this exception? I found this article that uses a delta to compare if minor time difference is failing the comparison but still unsure why I still need an extra function to compare date/time assertions.

Edit-1: Here is my date conversion method which I am testing

    public static DateTime GetDateTime(this long milliseconds)
    {
        try
        {
            return new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(milliseconds));
        }
        catch { throw; }
    }

Even though there is an alternate to this with new datetime(long), but logically whats wrong with this?

Upvotes: 1

Views: 3862

Answers (1)

Jamiec
Jamiec

Reputation: 136239

To the nearest second (the granularity the console is showing you) they are equal. To the nearest millisecond, they are not

long date = 1500024370374;
DateTime result = new DateTime(1970,1,1).AddMilliseconds(date);
DateTime comparisonDate = new DateTime(2017, 07, 14, 9, 26, 10);

Console.WriteLine(result.ToString("dd-MM-yyyy HH:mm:ss.fffff"));
// 14-07-2017 09:26:10.37400
Console.WriteLine(comparisonDate.ToString("dd-MM-yyyy HH:mm:ss.fffff"));
// 14-07-2017 09:26:10.00000

Live example: http://rextester.com/PYDLAD6594

Upvotes: 5

Related Questions