Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Epoch DateTime conversion

Tags:

c#

datetime

epoch

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!

like image 388
Rob McCabe Avatar asked Jun 30 '26 05:06

Rob McCabe


1 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.

like image 79
iakobski Avatar answered Jul 01 '26 21:07

iakobski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!