Last active
September 7, 2024 08:32
-
-
Save ramonsmits/75b49525c1fa8cd9bb7156f9de4f5983 to your computer and use it in GitHub Desktop.
Port DateTimeOffset.ToUnixTimeMilliseconds to DateTime for much faster and efficent handling of Unix Time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DateTimeOffset first converts internally to DateTime, if you only want to get Unix Time you would need to do: | |
// DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() which allocated more memory and is significantly slower due to | |
// embedding offset data based on the active timezone. | |
public static class DateTimeUnixTimeExtensions | |
{ | |
static readonly long UnixEpochTicks = DateTime.UnixEpoch.Ticks; | |
static readonly long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000 | |
public static long ToUnixTimeMilliseconds(this DateTime instance) | |
{ | |
return instance.Ticks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment