C# 时间和时间戳之间的转换

    时间格式的一些转换:

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

        /// <summary>
        /// 时间戳转成时间
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static DateTime TimestampToUnixDateTime(long t)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            return  startTime.AddSeconds(t);
        }

        /// <summary>
        /// Sat, 05 Nov 2005 14:06:25 GMT 
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToEnglishDateTimeString(DateTime dt )
        {
            if (dt != null)
            {
                string str = dt.GetDateTimeFormats('r')[0].ToString();//Sat, 05 Nov 2005 14:06:25 GMT 
                return str.Substring(4, str.Length - 11);
            }
            else
            {
                return null;
            }
        }

 

posted @ 2017-07-11 14:34  林子……  阅读(1557)  评论(0编辑  收藏  举报