How to get unix timestamp in C#

By FoxLearn 11/18/2024 6:45:26 AM   287
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.

A Unix timestamp, also known as a POSIX timestamp or epoch time, is a way of representing a specific point in time. It counts the number of seconds that have passed since January 1, 1970, at 00:00:00 UTC.

For example unix timestamp format:

1633024800 (which corresponds to October 1, 2021, 00:00:00 UTC).

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();