Unix time conversions in C# [duplicate]

“Unix timestamp” means seconds since the epoch in most situations rather than milliseconds… be careful! However, things like Java use “milliseconds since the epoch” which may be what you actually care about – despite the tool you showed. It really depends on what you need.

Additionally, you shouldn’t be doing anything with local time. Stick to universal time throughout.

I would have:

private static readonly DateTime UnixEpoch =
    new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public static long GetCurrentUnixTimestampMillis()
{
    return (long) (DateTime.UtcNow - UnixEpoch).TotalMilliseconds;
}

public static DateTime DateTimeFromUnixTimestampMillis(long millis)
{
    return UnixEpoch.AddMilliseconds(millis);
}

public static long GetCurrentUnixTimestampSeconds()
{
    return (long) (DateTime.UtcNow - UnixEpoch).TotalSeconds;
}

public static DateTime DateTimeFromUnixTimestampSeconds(long seconds)
{
    return UnixEpoch.AddSeconds(seconds);
}

Leave a Comment