Home > Backend Development > C++ > How to Convert Epoch Time to a Human-Readable Date and Time in C#?

How to Convert Epoch Time to a Human-Readable Date and Time in C#?

Patricia Arquette
Release: 2025-01-26 08:06:11
Original
448 people have browsed it

How to Convert Epoch Time to a Human-Readable Date and Time in C#?

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)
  • To get a standard 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);
}
Copy after login

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!

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