C#时间戳转换





/// <summary>
/// 日期转换成unix时间戳
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static long DateTimeToUnixTimestamp(DateTime dateTime)
{
    var start = new DateTime(1970, 1, 1, 0, 0, 0, dateTime.Kind);
    return Convert.ToInt64((dateTime - start).TotalSeconds);
}

/// <summary>
/// unix时间戳转换成日期
/// </summary>
/// <param name="unixTimeStamp">时间戳(秒)</param>
/// <returns></returns>
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

打赏

取消 我去学网

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少
微信

打开微信扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

  1. #2

    木庄网络博客(2016/10/28 11:41:03)
    不错的网站主题,看着相当舒服

  2. #1

    木庄网络博客(2016/10/14 21:02:39)
    博客做得好漂亮哦!