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
Release: 2025-01-26 08:21:13
Original
852 people have browsed it

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:

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);
}
Copy after login

Retrieving DateTime from DateTimeOffset:

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

DateTime dateTime = dateTimeOffset.DateTime;
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template