How to get unix timestamp in C#

By FoxLearn 7/11/2024 9:00:05 AM   32
In C#, you can get the Unix timestamp, which represents the number of seconds that have elapsed since January 1, 1970 (Unix epoch), in a couple of ways.

You can use DateTimeOffset and ToUnixTimeSeconds() to get unix timestamp in C#

// Get the current DateTimeOffset
DateTimeOffset dto = DateTimeOffset.Now;

// Convert to Unix timestamp (seconds since Jan 1, 1970)
long unixTime = dto.ToUnixTimeSeconds();

// Unix timestamp (seconds): 1720687008

Uses DateTimeOffset which directly provides the ToUnixTimeSeconds() method to get the Unix timestamp.

You can also use DateTime and manual calculation to get unix timestamp in C#

// Get the current DateTime in UTC
DateTime dt = DateTime.UtcNow;

// Convert to Unix timestamp (seconds since Jan 1, 1970)
long unixTime = (long)(dt.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

// Unix timestamp (seconds): 1720687153

Uses DateTime.UtcNow to get the current UTC time, subtracts the Unix epoch (January 1, 1970 UTC), and converts the resulting TimeSpan to seconds.

How to convert seconds unix timestamp to DateTimeOffset type (UTC)

// Unix timestamp in seconds
long unixTimestamp = 1720687153; // Replace with your Unix timestamp

// Convert Unix timestamp to DateTimeOffset
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(unixTimestamp);
        
// Convert to UTC
DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime();

// Output the DateTimeOffset (UTC): 2024-07-11 08:39:13 +00:00
Console.WriteLine(dateTimeOffset.ToString("yyyy-MM-ddTHH:mm:ss.fffK"));

How to convert milliseconds unix timestamp to DateTimeOffset type (UTC)

// Example Unix timestamp in milliseconds
long unixTimestampMilliseconds = 1720687153000; // Replace this with your Unix timestamp in milliseconds

// Create DateTimeOffset object in UTC
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(unixTimestampMilliseconds);

// Ensure it's in UTC
dateTimeOffset = dateTimeOffset.ToUniversalTime();

// Output the DateTimeOffset UTC: 2024-07-11T08:39:13.000+00:00
Console.WriteLine(dateTimeOffset.ToString("yyyy-MM-ddTHH:mm:ss.fffK"));

How to convert current UTC time to unix timestamp in seconds

// Example Unix timestamp in seconds: 1720688109
long unixTimestampSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

How to convert current UTC time to unix timestamp in milliseconds

// Example Unix timestamp in milli seconds: 1720688075851
long unixTimestampMilliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();