I am working with .NET but I need to communicate with a logging service, unix based, that expects seconds and microseconds since the Unix epoch time. The seconds is easily retrievable doing something like:
DateTime UnixEpoch = new DateTime(1970, 1, 1);
TimeSpan time = DateTime.UtcNow() - UnixEpoch
int seconds = (int) time.TotalSeconds
however, I am unsure how to calculate the microseconds. I could use the TotalMilliseconds property and convert it to microseconds but I believe that defeats the purpose of using microseconds as a precise measurement. I have looked into using the StopWatch class but it doesn’t seem like I can seed it with a time (Unix Epoch for example).
Thanks.
Use the
Ticksproperty to get the most fine-grained level of detail. A tick is 100ns, so divide by 10 to get to microseconds.However, that talks about the representation precision – it doesn’t talk about the accuracy at all. Given the coarse granularity of
DateTime.UtcNowI wouldn’t expect it to be particularly useful. See Eric Lippert’s blog post about the difference between precision and accuracy for more information.You may want to start a stopwatch at a known time, and basically add its time to the “start point”. Note that “ticks” from
Stopwatchdoesn’t mean the same asTimeSpan.Ticks.