Home >Backend Development >C++ >How Do I Convert Unix Epoch Time to a Real-Time DateTime Object in C#?

How Do I Convert Unix Epoch Time to a Real-Time DateTime Object in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-26 08:21:13790browse

How Do I Convert Unix Epoch Time to a Real-Time DateTime Object in C#?

Effortlessly Convert Unix Epoch Time to DateTime in C#

Unix epoch time signifies the seconds elapsed since January 1st, 1970, 00:00:00 UTC. This guide demonstrates how to efficiently convert this to a C# DateTime object.

Modern .NET (>= 2.1): The Simplest Approach

.NET Core 2.1 and later offer streamlined methods:

  • DateTime.UnixEpoch.AddSeconds(epochSeconds)
  • DateTime.UnixEpoch.AddMilliseconds(epochMilliseconds)

These directly add the epoch offset (in seconds or milliseconds) to the base Unix epoch time.

Older .NET Versions:

For versions prior to .NET Core 2.1, utilize this concise function:

<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>

Retrieving DateTime from DateTimeOffset:

To extract a DateTime object from a DateTimeOffset, simply use:

<code class="language-csharp">DateTime dateTime = dateTimeOffset.DateTime;</code>

Important Update Note:

This solution has been updated for compatibility across different .NET versions. For optimal performance in newer .NET versions, leverage the DateTime.UnixEpoch methods.

The above is the detailed content of How Do I Convert Unix Epoch Time to a Real-Time DateTime Object in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn