C#时间戳转换=

发布时间:2015-08-30 05:30:16

C#时间戳转换

基于.net的应用中,不会用到unix时间戳,当.net应用与其它应用(eg: php, java)交互时,就会用到unix时间戳。在项目中曾经用到过一次,用户通过web app提交数据并分享给安卓app时,如果时间间隔在一分钟内,数据才能算是真实有效,否则不予处理。还有asp.net开发中,经常会需要将对象序列化成json数据,js拼接成html,日期对象就会被序列化成如下形式:{“date”:”\/Date(1349839763373)\/”},js还无法识别,这时就不妨考虑下将日期转换成unix时间戳。

以下是C#下的日期与unix时间戳的相互转换:

///

/// 日期转换成unix时间戳

///

///

///

public static long DateTimeToUnixTimestamp(DateTime dateTime)

{

var start = new DateTime(1970, 1, 1, 0, 0, 0, dateTime.Kind);

return Convert.ToInt64((dateTime - start).TotalSeconds);

}

///

/// unix时间戳转换成日期

///

/// 时间戳(秒)

///

public static DateTime UnixTimestampToDateTime(this DateTime target, long timestamp)

{

var start = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);

return start.AddSeconds(timestamp);

}

说下这个日期(1970-1-1),现在计算机和一些电子设备时间的计算和显示是以距历元(即格林威治标准时间 1970 年 1 月 1 日的 00:00:00.000,格里高利历)的偏移量为标准的,有人就戏称英国的格林威治天文台是“时间开始的地方”。

 

附:

1. 各语言的时间戳转换:http://www.epochconverter.com/

2. unix时间介绍:http://en.wikipedia.org/wiki/Unix_time

C#时间戳转换=

相关推荐