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:
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; }
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; }
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!