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
Patricia ArquetteOriginal
2025-02-01 23:51:11590browse

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:

<code class="language-csharp">public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
    DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return dateTime.AddSeconds(unixTimeStamp).ToLocalTime();
}</code>

From DateTime to Unix Timestamp

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

<code class="language-csharp">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;
}</code>

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