Skip to content

Instantly share code, notes, and snippets.

@glopesdev
Created June 21, 2023 22:24
Show Gist options
  • Select an option

  • Save glopesdev/33353eac98b71494a383bab1ca69bb90 to your computer and use it in GitHub Desktop.

Select an option

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