I need to work with epoch times in c# and I have created the following two extension methods to do so:
public static DateTime ToDateTime(this double epochTime)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epochTime);
}
public static double ToEpochTime(this DateTime dt)
{
var t = dt - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return t.TotalSeconds;
}
I get a failure when I run the following test:
[Fact]
public void Test_EpochTime()
{
var dateToTest = DateTime.Now;
var epoch = dateToTest.ToEpochTime();
var result = epoch.ToDateTime();
Assert.Equal(result, dateToTest);
}
The result is:
Xunit.Sdk.EqualException: 'Assert.Equal() Failure
Expected: 2020-03-02T17:43:19.1830000Z
Actual: 2020-03-02T17:43:19.1831870+00:00'
Has anyone experienced this before, where there's an issue converting between the double/DateTime?
Thanks for any pointers in advance!