C#本地时间转Unix时间

  1. 获取Unix时间最高效的方法
       /// <summary>
        /// 扩展方法, 本地时间转Unix时间; (如 本地时间 "2020-01-01 20:20:10" 转换unix后等于 1577881210)
        /// </summary>
        /// <param name="time">本地时间</param>
        /// <returns>基于秒的10位数</returns>
        public static long GetTimeStamp2(this DateTime time)
        {
            return time.ToUniversalTime().Ticks / 10000000 - 62135596800;
        }
  1. 另外一种容易理解 但是效率略低的写法

	/// <summary>
        /// 扩展方法, 本地时间转Unix时间; (如 本地时间 "2020-01-01 20:20:10" 转换unix后等于 1577881210)
        /// </summary>
        /// <param name="time">本地时间</param>
        /// <returns>基于秒的10位数</returns>
        public static long GetTimeStamp2(this DateTime time)
        {
            return (long)(time.ToUniversalTime() -
                    new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
        }
  1. 基于字符串转Unix时间
    string fmtDate ="yyyy-MM-dd";//也可以是别的格式,如 "ddd MMM d HH:mm:ss 'UTC'zz'00' yyyy"
    string strTimeToParse="1970-01-01";//待转换的时间,格式需要和fmtDate 一致
    CultureInfo cInfo = CultureInfo.CreateSpecificCulture("en-US");//unix
    DateTime.ParseExact(strTimeToParse, fmtDate, cInfo);//转成Unix时间 
    //string JSstring = DateTime.Now.ToString(fmtDate, cInfo);//将C#时间转换成JS时间字符串 

题外话:

例子 类型
DateTime.Now.Ticks long
stopwatch.Elapsedxxx(如TotalDays,TotalSeconds,TotalMilliseconds) long
TimeSpan.Totalxxxx(如TotalDays,TotalSeconds,TotalMilliseconds) double
stopwatch.Elapsed.Totalxxxx double

关于Tick ,一个 'Tick' 周期是 is 100 纳秒(ns,nsec,mnanosecond ).
1 毫秒(millisecond ) 等于 1000 微妙(microsecond) ,等于100 000纳秒;
2 据说Totalxxx的内部实现是基于Ticks;
tick并不基于 CPU的时钟周期,但是Tick的计数或根据CPU时钟发生变化( 2G MZ的CPU来说,大概20个CPU时钟周期,新增1个Tick )

原文地址:https://www.cnblogs.com/francisXu/p/13098059.html