Comprehensive Guide to Converting DateTime to Unix Timestamp in C#

Nov 24, 2025 · Programming · 8 views · 7.8

Keywords: C# | DateTime | Unix Timestamp | Time Conversion | .NET

Abstract: This article provides an in-depth exploration of methods for converting DateTime to Unix timestamp (seconds since January 1, 1970) in C#. By analyzing the internal implementation of DateTime, it详细介绍s the classic conversion approach based on TimeSpan calculations and offers complete bidirectional conversion code examples. The article also compares improvements across different .NET versions, including the DateTime.UnixEpoch static property introduced in .NET Core 2.1, and the convenient approach using DateTimeOffset. All code is optimized and thoroughly commented to ensure reliable application in real-world projects.

Fundamental Concepts of DateTime and Unix Timestamp

In C# programming, the DateTime structure represents a point in time, internally implemented as the number of 100-nanosecond intervals (called "ticks") since 12:00:00 midnight, January 1, 0001. The Unix timestamp, however, is defined as the number of seconds that have elapsed since 00:00:00 UTC on January 1, 1970 (known as the Unix epoch). These two time representations have different reference points, necessitating precise conversion.

Core Conversion Principle Analysis

The conversion from DateTime to Unix timestamp essentially involves calculating the time difference between two points. Key steps include: determining the Unix epoch reference point, computing the time interval, and converting the interval to seconds. It is important to note that since DateTime may contain local timezone information while Unix timestamp is based on UTC, timezone unification must be performed.

Standard Conversion Method Implementation

Below is the optimized complete conversion method, including bidirectional conversion functionality:

public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    return origin.AddSeconds(timestamp);
}

public static double ConvertToUnixTimestamp(DateTime date)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    TimeSpan diff = date.ToUniversalTime() - origin;
    return Math.Floor(diff.TotalSeconds);
}

Method Details Analysis

In the ConvertToUnixTimestamp method, the input time is first converted to UTC time via date.ToUniversalTime(), ensuring timezone consistency with the Unix epoch. The time difference from the reference point is then calculated, and Math.Floor is used to ensure integer seconds are returned, avoiding potential issues with fractional parts. The ConvertFromUnixTimestamp method reconstructs the DateTime object by adding the specified seconds to the reference point.

Improvements in .NET Core 2.1 and Later

Starting from .NET Core 2.1 and .NET Standard 2.1, the framework provides the DateTime.UnixEpoch static property, allowing direct access to the Unix epoch point:

DateTime origin = DateTime.UnixEpoch;

This eliminates potential errors when manually creating the reference point and improves code readability and maintainability.

Alternative Approach Using DateTimeOffset

If the system permits using DateTimeOffset instead of DateTime, a more concise conversion method can be employed:

long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();

This method directly returns a 64-bit integer, avoiding floating-point precision issues, though additional conversion may be needed when integrating with existing DateTime code.

Performance and Precision Considerations

In performance-sensitive scenarios, avoid repeatedly creating DateTime reference point objects. Consider defining the reference point as a static readonly field:

private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

Regarding precision, note that DateTime has 100-nanosecond precision, while Unix timestamp typically only goes to second-level, resulting in the loss of sub-second information during conversion.

Practical Application Recommendations

In actual projects, it is recommended to encapsulate conversion methods into utility classes and provide appropriate exception handling. For high-concurrency scenarios, ensure method thread safety. Additionally, considering timezone issues, strongly recommend using UTC time for all time processing, converting to local time only when displaying.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.