Home > Backend Development > C++ > How to Convert Between Unix Timestamps and DateTime Objects in C#?

How to Convert Between Unix Timestamps and DateTime Objects in C#?

Patricia Arquette
Release: 2025-02-01 23:51:11
Original
643 people have browsed it

How to Convert Between Unix Timestamps and DateTime Objects in C#?

Efficiently Handling Unix Timestamps and DateTime Objects in C#

Data processing often involves converting between Unix timestamps and DateTime objects. Unix timestamps, representing seconds since the Unix epoch (January 1, 1970), are compact for storage and transmission. DateTime objects offer better human readability and flexibility.

From Unix Timestamp to DateTime

This C# function converts a Unix timestamp (in seconds) to a DateTime object:

public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
    DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return dateTime.AddSeconds(unixTimeStamp).ToLocalTime();
}
Copy after login

From DateTime to Unix Timestamp

Conversely, this function converts a DateTime object to a Unix timestamp:

public static double DateTimeToUnixTimeStamp(DateTime dateTime)
{
    DateTime utcDateTime = dateTime.ToUniversalTime();
    TimeSpan span = utcDateTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return span.TotalSeconds;
}
Copy after login

Important Consideration: Accurate time zone handling is crucial when converting timestamps across different time zones to avoid errors. The provided code uses ToUniversalTime() to ensure consistent results.

The above is the detailed content of How to Convert Between Unix Timestamps and DateTime Objects 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