C# Epoch DateTime conversion

Viewed 697

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!

2 Answers

A double only has enough precision to hold down to milliseconds. If you want more precision, you will have to use DateTime.Ticks which is a long. A long is an exact value, it won't change.

If you want milliseconds, then as @Magnetron points out, there are built-in methods for that. Above all, and this is general advice, if you need an exact value, don't use double or float types.

For me the solution was to change and use Ticks for greater precision (thanks @iakobski). Here's the updated extension methods:

public static DateTime ToDateTime(this long epochTime)
{
    return new DateTime(1970, 1, 1, 0, 0, 0).AddTicks(epochTime);
}

public static long ToEpochTime(this DateTime dt)
{
    var t = dt.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0);
    return t.Ticks;
}
Related