zoukankan      html  css  js  c++  java
  • C#时间戳和DateTime转换

    时间戳:格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总时间。(中国为东8区 )

    Unix时间戳转DateTime:

     1         /// <summary>
     2         /// Unix时间戳转DateTime
     3         /// </summary>
     4         /// <param name="timestamp">时间戳</param>
     5         /// <returns></returns>
     6         public static DateTime ConvertToDateTime(string timestamp)
     7         {
     8             DateTime time = DateTime.MinValue;
     9             DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970,1,1));
    10             if (timestamp.Length==10)        //精确到秒
    11             {
    12                 time=startTime.AddSeconds(double.Parse(timestamp));
    13             }
    14             else if (timestamp.Length ==13)   //精确到毫秒
    15             {
    16                 time = startTime.AddMilliseconds(double.Parse(timestamp));
    17             }
    18             return time;
    19         }

    DateTime转时间戳:

     1         /// <summary>
     2         /// DateTime转时间戳
     3         /// </summary>
     4         /// <param name="time">DateTime时间</param>
     5         /// <param name="type">0为毫秒,1为秒</param>
     6         /// <returns></returns>
     7         public static string ConvertTimestamp(DateTime time,int type=0)
     8         {
     9             double intResult = 0;
    10             DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
    11             if (type==0)
    12             {
    13                 intResult = (time - startTime).TotalMilliseconds;
    14             }
    15             else if (type == 1)
    16             {
    17                 intResult = (time - startTime).TotalSeconds;
    18             }
    19             else
    20             {
    21                 Console.WriteLine("参数错误!");
    22             }
    23             return Math.Round(intResult, 0).ToString();
    24         }

     Tips:注意北京时间和格林威治时间

  • 相关阅读:
    编辑器 --- Visual Studio Code 英文界面转换成中文(简体)
    CSS3 -- column 实现瀑布流布局
    CSS3 -- 边框圆角
    CSS3 -- 弹性盒
    自适应布局要素
    Vue -- 基础知识
    Vue -- element-ui el-table 的合计在第一行显示并可点击
    如何在网页标题栏title加入logo(icon)图标?
    linux下暴力破解工具hydra【转】
    linux 服务简介
  • 原文地址:https://www.cnblogs.com/mariolz/p/13265808.html
Copyright © 2011-2022 走看看