Home > Backend Development > C++ > How Can I Convert Epoch Time to Real Time in C#?

How Can I Convert Epoch Time to Real Time in C#?

Barbara Streisand
Release: 2025-01-26 08:16:09
Original
818 people have browsed it

How Can I Convert Epoch Time to Real Time in C#?

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)
  • To get a DateTime object: DateTime dateTime = dateTimeOffset.DateTime

Legacy Approach:

While functional, this method is less concise than the modern alternatives:

  1. Define an epoch starting point: private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  2. Create a conversion method: public static DateTime FromUnixTime(long unixTime)
  3. Perform the conversion: 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!

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