Home > Backend Development > C#.Net Tutorial > Example code for DateTime and timestamp conversion in C#

Example code for DateTime and timestamp conversion in C#

黄舟
Release: 2017-06-18 10:33:49
Original
3289 people have browsed it

本篇文章主要介绍了C# DateTime与时间戳转换实例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

C# DateTime与时间戳的相互转换,包括JavaScript时间戳和Unix的时间戳。

1. 什么是时间戳

首先要清楚JavaScript与Unix的时间戳的区别:

JavaScript时间戳:是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总毫秒数。

Unix时间戳:是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

可以看出JavaScript时间戳总毫秒数,Unix时间戳是总秒数。

比如同样是的 2016/11/03 12:30:00 ,转换为JavaScript时间戳为 1478147400000;转换为Unix时间戳为 1478147400。

2. JavaScript时间戳相互转换

2.1 C# DateTime转换为JavaScript时间戳

System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区

long timeStamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // 相差毫秒数

System.Console.WriteLine(timeStamp);
Copy after login

2.2 JavaScript时间戳转换为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"));
Copy after login

3. Unix时间戳相互转换

3.1 C# DateTime转换为Unix时间戳


System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区

long timeStamp = (long)(DateTime.Now - startTime).TotalSeconds; // 相差秒数

System.Console.WriteLine(timeStamp);
Copy after login

3.2 Unix时间戳转换为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"));
Copy after login

The above is the detailed content of Example code for DateTime and timestamp conversion in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template