c#DateTime与unix时间戳互相转换


https://www.cnblogs.com/yaosj/p/11230626.html

因为七牛的私库下载路径中的超时时间需要用到Unix时间戳,特此记录一下

Unix时间戳( Unix timestamp):从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public  class  UnixTimeUtil
{
     /// <summary>
     /// 将dateTime格式转换为Unix时间戳
     /// </summary>
     /// <param name="dateTime"></param>
     /// <returns></returns>
     public  static  int  DateTimeToUnixTime(DateTime dateTime)
     {
         return  ( int )(dateTime - TimeZone.CurrentTimeZone.ToLocalTime( new  DateTime(1970, 1, 1))).TotalSeconds;
     }
 
     /// <summary>
     /// 将Unix时间戳转换为dateTime格式
     /// </summary>
     /// <param name="time"></param>
     /// <returns></returns>
     public  static  DateTime UnixTimeToDateTime( int  time)
     {
         if  (time < 0)
             throw  new  ArgumentOutOfRangeException( "time is out of range" );
 
         return  TimeZone.CurrentTimeZone.ToLocalTime( new  DateTime(1970, 1, 1)).AddSeconds(time);
     }
}

  

还可以这样子求Unix时间戳:

(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM