In C# you can easily convert a DateTimeOffset to Unix time in seconds or miliseconds using the built-in methods ToUnixTimeSeconds
or ToUnixTimeMilliseconds
:
var dateTimeOffset = DateTimeOffset.Now;
var unixTimeInSeconds = dateTimeOffset.ToUnixTimeSeconds();
var unixTimeMiliseconds = dateTimeOffset.ToUnixTimeMilliseconds();
The DateTime struct does not have this built-in method, so in order to use this you can convert your DateTime into a DateTimeOffset first:
var dateTimeOffset = new DateTimeOffset(DateTime.Now);
var unixTimeInSeconds = dateTimeOffset.ToUnixTimeSeconds();
var unixTimeMiliseconds = dateTimeOffset.ToUnixTimeMilliseconds();
You can create a DateTimeOffset
from a unix time stamp in seconds or miliseconds using the built in FromUnixTimeSeconds
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1669321628392);
DateTimeOffset dateTimeOffset2 = DateTimeOffset.FromUnixTimeSeconds(1669321628);
In order to get a DateTime
form a unix timestamp you can use the above and then convert the DateTimeOffset
to a DateTime
:
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1669321628392);
var dateTime = dateTimeOffset.DateTime;
That is all!
I hope you found the above helpful, please a leave a comment down below if you did!