A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in C#.
To run the program, compile and execute it:
In C#, we use DateTime.UtcNow to get the current UTC time. To calculate the time since the Unix epoch, we create a DateTimeOffset representing the Unix epoch and subtract it from the current time.
The TimeSpan class provides properties like TotalSeconds and TotalMilliseconds for easy conversion. For nanoseconds, we multiply Ticks by 100 (as each tick is 100 nanoseconds).
To convert back from seconds or nanoseconds to DateTime, we use the AddSeconds and AddTicks methods on the Unix epoch DateTimeOffset.
Next, we’ll look at another time-related task: time parsing and formatting.