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

How to Convert Between Unix Timestamps and .NET DateTime Objects?

Susan Sarandon
Release: 2025-02-01 23:56:10
Original
1021 people have browsed it

How to Convert Between Unix Timestamps and .NET DateTime Objects?

Easily convert UNIX timestamp and .NET DATETIME objects

UNIX timestamp is a common method in the calculation field. This article will introduce how to easily convert the UNIX timestamp in C#to .NET DATETIME objects and reverse conversion methods.

from UNIX timestamp to datetime

The UNIX timestamp (from the UNIX Age, that is, the number of seconds of the second UTC of UTC on January 1, 1970) to the Datetime object in C#is very simple:

From datetime to UNIX timestamp

public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
    // Unix时间戳表示自纪元以来的秒数
    DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    dateTime = dateTime.AddSeconds(unixTimeStamp).ToLocalTime();
    return dateTime;
}
Copy after login

On the contrary, it is also simple to convert the DateTime object back to the UNIX timestamp:

Java Precautions

public static double DateTimeToUnixTimeStamp(DateTime dateTime)
{
    // 转换为UTC时间以避免夏令时问题
    dateTime = dateTime.ToUniversalTime();
    // 计算自Unix纪元以来的秒数
    double unixTimeStamp = (dateTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
    return unixTimeStamp;
}
Copy after login
Java uses milliseconds to indicate UNIX timestamps, while .NET used seconds. Please adjust the conversion function in the Java code as needed.

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