当前位置: 移动技术网 > IT编程>开发语言>c# > C# DateTime与时间戳转换实例

C# DateTime与时间戳转换实例

2019年07月18日  | 移动技术网IT编程  | 我要评论

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); 

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")); 

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); 

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")); 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网