zoukankan      html  css  js  c++  java
  • C# 时间戳与时间的相互转换

    时间戳实际就是当前时间距离1970年1月1日0点0时0分0秒(转换成北京时间是1970年1月1日8点0时0分0秒)距离你要计算的时间的秒数或者毫秒数
    一般来说:我们用的时间戳到秒的话是10位,到毫秒的话是13位

    一、时间time与秒时间戳之间转换

    1、把时间time转换成秒时间戳

      DateTime time = DateTime.Now;
      System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区
      TimeSpan ts = time - startTime; 
      var timestamp = Convert.ToInt64(ts.TotalSeconds);
      Console.WriteLine(timestamp);
    

    2、秒时间戳转换成time

      long timestamp=1629160713;
      System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区
      var time = startTime.AddSeconds(timestamp);
    

    二、时间time与毫秒时间戳之间转换

    1、把时间time转换成毫秒时间戳

      TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
      var timestamp= Convert.ToInt64(ts2.TotalMilliseconds);
      Console.WriteLine(timestamp);
    

    2、毫秒时间戳转换成time

      System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区  
      var time = startTime.AddMilliseconds(cc);
    

    注意点:
    UtcNow 获取的是标准时区,而TimeZone.CurrentTimeZone.ToLocalTime获取的是当地时区,所以获取时间差会有两种写法

      //当地时区
      System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
      TimeSpan ts = DateTime.Now - startTime; 
    
      //标准时区
      TimeSpan ts2 = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
    
  • 相关阅读:
    查看python关键字
    命令终端执行python
    Codeforces-462C. A Twisty Movement
    Codeforces-462A. A Compatible Pair
    Codeforces-446C. Pride
    Codeforces-Hello 2018C. Party Lemonade(贪心)
    Codeforces-33C. Wonderful Randomized Sum
    Codeforces-118D. Caesar's Legions(lazy dynamics)
    codeforces-73C. LionAge II
    Gym 101510C-Computer Science
  • 原文地址:https://www.cnblogs.com/qingheshiguang/p/15150813.html
Copyright © 2011-2022 走看看