Created
June 21, 2023 22:24
-
-
Save glopesdev/33353eac98b71494a383bab1ca69bb90 to your computer and use it in GitHub Desktop.
A utility helper class for converting 64-bit ticks to doubles with minimal loss of precision
This file contains hidden or 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
| using System; | |
| static class TimeConverter | |
| { | |
| const double SecondsPerTick = 1.0 / TimeSpan.TicksPerSecond; | |
| public static double GetTimestamp(TimeSpan timeSpan) | |
| { | |
| return GetTimestamp(timeSpan.Ticks); | |
| } | |
| public static double GetTimestamp(long ticks) | |
| { | |
| var integral = (ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond; | |
| var fractional = ticks - integral; | |
| return (integral * SecondsPerTick) + | |
| (fractional * SecondsPerTick); | |
| } | |
| public static long ToTicks(double seconds) | |
| { | |
| var integral = Math.Truncate(seconds); | |
| var fractional = seconds - integral; | |
| return (long)(integral * TimeSpan.TicksPerSecond) + | |
| (long)(fractional * TimeSpan.TicksPerSecond); | |
| } | |
| public static TimeSpan ToTimeSpan(double seconds) | |
| { | |
| return new TimeSpan(ToTicks(seconds)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment