Home >Backend Development >C++ >How to Convert Epoch Time to Real Time in C#?
C# Epoch Time to Real Time Conversion Methods
This guide demonstrates how to convert Unix epoch time (seconds since January 1, 1970, UTC) to a readable date and time in C#. Several approaches cater to different .NET versions.
Modern .NET (Core >= 2.1 and later):
The simplest method leverages built-in functions:
<code class="language-csharp">DateTime realTime = DateTime.UnixEpoch.AddSeconds(epochSeconds); // For seconds DateTime realTimeMillis = DateTime.UnixEpoch.AddMilliseconds(epochMilliseconds); // For milliseconds</code>
Using DateTimeOffset (Recommended since 2020):
DateTimeOffset
provides improved time zone handling:
<code class="language-csharp">DateTimeOffset realTimeOffset = DateTimeOffset.FromUnixTimeSeconds(epochSeconds); // For seconds DateTimeOffset realTimeOffsetMillis = DateTimeOffset.FromUnixTimeMilliseconds(epochMilliseconds); // For milliseconds DateTime realTime = realTimeOffset.DateTime; // Extract DateTime if needed</code>
For Older .NET Versions (Pre-2020):
For older .NET frameworks lacking the above methods, a custom function is necessary:
<code class="language-csharp">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); }</code>
This function adds the given unixTime
(in seconds) to the Unix epoch, resulting in a DateTime
object representing the real time. Remember to handle potential exceptions (e.g., ArgumentOutOfRangeException
).
Choose the method most appropriate for your .NET version. DateTimeOffset
is generally preferred for its enhanced precision and time zone awareness.
The above is the detailed content of How to Convert Epoch Time to Real Time in C#?. For more information, please follow other related articles on the PHP Chinese website!