C# Epoch Time Conversion: Human-Readable Dates and Times
Epoch time, representing seconds since January 1, 1970, 00:00:00 UTC, can be easily converted to a user-friendly date and time format in C#. This guide explores several methods.
Modern .NET Approaches (.NET Core 2.1 and later):
The most straightforward approach in recent .NET versions involves using DateTime.UnixEpoch
:
DateTime.UnixEpoch.AddSeconds(epochSeconds)
: Adds the specified number of seconds to the epoch, yielding a DateTime
object.DateTime.UnixEpoch.AddMilliseconds(epochMilliseconds)
: Similar to the above, but uses milliseconds.Leveraging DateTimeOffset:
For more precise time zone handling, consider DateTimeOffset
:
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(epochSeconds)
DateTimeOffset dateTimeOffset2 = DateTimeOffset.FromUnixTimeMilliseconds(epochMilliseconds)
DateTime
object: DateTime dateTime = dateTimeOffset.DateTime
Classic Method (for older .NET frameworks):
If you're working with older .NET versions lacking the above methods, this utility function provides the same functionality:
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); }
This function adds the unixTime
(in seconds) to the epoch start time. Remember to adjust for milliseconds if necessary.
The above is the detailed content of How to Convert Epoch Time to a Human-Readable Date and Time in C#?. For more information, please follow other related articles on the PHP Chinese website!