Converting Unix Epoch Time to a Human-Readable Date and Time in C#
This guide demonstrates several methods to convert Unix epoch time (seconds or milliseconds since January 1, 1970, 00:00:00 UTC) into a standard date and time format within C#.
Modern Approaches (.NET Core 2.1 and later):
For optimal efficiency in newer .NET versions, leverage these built-in methods:
AddSeconds
: DateTime.UnixEpoch.AddSeconds(epochSeconds)
(for epoch time in seconds)AddMilliseconds
: DateTime.UnixEpoch.AddMilliseconds(epochMilliseconds)
(for epoch time in milliseconds)Alternative Method (Suitable for older .NET versions):
This approach utilizes DateTimeOffset
for enhanced precision and handling of time zones:
DateTimeOffset
:DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(epochSeconds)
DateTimeOffset dateTimeOffset2 = DateTimeOffset.FromUnixTimeMilliseconds(epochMilliseconds)
DateTime
object: DateTime dateTime = dateTimeOffset.DateTime
Legacy Approach:
While functional, this method is less concise than the modern alternatives:
private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static DateTime FromUnixTime(long unixTime)
return epoch.AddSeconds(unixTime);
Choose the method best suited to your .NET framework version and coding style. The modern AddSeconds
and AddMilliseconds
approaches are generally preferred for their simplicity and performance.
The above is the detailed content of How Can I Convert Epoch Time to Real Time in C#?. For more information, please follow other related articles on the PHP Chinese website!