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 Ticks
property 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.UtcNow
I 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 Stopwatch
doesn't mean the same as TimeSpan.Ticks
.
From Epoch Converter:
epoch = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
This will truncate it because of integer division, so make it 10000000.0
to maintain the sub-second portion, or just don't do the division.
It's important to note that the .Ticks
property you get is relative to Jan 1, 0001 and not Jan 1, 1970 like in UNIX which is why you need to subtract that offset above.
edit: just for clarity, that nasty constant is just the number of ticks between Jan 1, 0001 and Jan 1, 1970 in UTC. If you take the seconds portion of it (62135596800
) and divide by (365 * 24 * 60 * 60) you see you get a number close to 1970
, which is of course not exactly 1970 due to leap adjustments.
DateTime.Ticks represent units of 100 nanoseconds since Jan. 1, 0001.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With