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

 

end c#文章导航
菜单加载中…