How can I get the current unix timestamp in microseconds in .NET 5? I have looked around and only found a way to get it in milliseconds with ToUnixTimeMilliseconds
, and nothing that would include microseconds.
CodePudding user response:
You just need to subtract the Unix epoch (1970-01-01T00:00:00Z) from the DateTimeOffset
to get a TimeSpan
, then get the microseconds from that by dividing the total number of ticks by 10:
using System;
public static class DateTimeOffsetExtensions
{
private static readonly DateTimeOffset UnixEpoch =
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
public static long ToUnixTimeMicroseconds(this DateTimeOffset timestamp)
{
TimeSpan duration = timestamp - UnixEpoch;
// There are 10 ticks per microsecond.
return duration.Ticks / 10;
}
}
public class Test
{
static void Main()
{
DateTimeOffset now = DateTimeOffset.UtcNow;
Console.WriteLine(now.ToUnixTimeMicroseconds());
}
}