Home  >  Article  >  Backend Development  >  C# DateTime and timestamp conversion

C# DateTime and timestamp conversion

高洛峰
高洛峰Original
2016-11-04 14:57:173032browse

C# DateTime and timestamp conversion, including JavaScript timestamps and Unix timestamps.

1. What is a timestamp?

First of all, we must understand the difference between JavaScript and Unix timestamps:

JavaScript timestamp: refers to 00:00:00 on January 1, 1970, Greenwich Mean Time (Beijing time The total number of milliseconds from January 1, 1970 (08:00:00) to the present.

Unix timestamp: refers to the total number of seconds from 00:00:00 on January 1, 1970, Greenwich Time (08:00:00 on January 1, 1970, Beijing time) to the present.

You can see that the JavaScript timestamp is the total number of milliseconds, and the Unix timestamp is the total number of seconds.

For example, the same 2016/11/03 12:30:00 , converted to JavaScript timestamp is 1478147400000; converted to Unix timestamp is 1478147400.

2. Convert JavaScript timestamps to each other

2.1 Convert C# DateTime to JavaScript timestamp

System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
long timeStamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // 相差毫秒数
System.Console.WriteLine(timeStamp);

2.2 Convert JavaScript timestamp to C# DateTime

long jsTimeStamp = 1478169023479;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
DateTime dt = startTime.AddMilliseconds(jsTimeStamp);
System.Console.WriteLine(dt.ToString("yyyy/MM/dd HH:mm:ss:ffff"));

3. Convert Unix timestamps to each other

3.1 Convert C# DateTime to Unix time Poke

System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
long timeStamp = (long)(DateTime.Now - startTime).TotalSeconds; // 相差秒数
System.Console.WriteLine(timeStamp);

3.2 Convert Unix timestamp to C# DateTime

long unixTimeStamp = 1478162177;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
DateTime dt = startTime.AddSeconds(unixTimeStamp);
System.Console.WriteLine(dt.ToString("yyyy/MM/dd HH:mm:ss:ffff"));

The above is the content of C# DateTime and timestamp conversion. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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
Previous article:NoneNext article:C++程序员Protocol Buffers基础指南