C# 时间戳 转 时间 时间转时间戳


最近遇到了一个问题 时间戳 时间的转化问题网上搜了很多没有一个系统的介绍,特此写此文以勉自己与后者在最短的时间内解决问题。

/// <summary>
    /// 时间戳
    /// </summary>
    public class TimeHelp
    {
        #region 时间戳[10|13]转为C#格式时间  
        /// <summary>
        ///  时间戳[10|13]转为C#格式时间       
        /// </summary>
        public static DateTime StampToDateTime(string stamp)
        {
            if (stamp.Length != 10 || stamp.Length != 13) return DateTime.Now;
            try
            {
                DateTime StartDateTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"));
                if (stamp.Length == 10) StartDateTime.AddSeconds(long.Parse(stamp));
                return StartDateTime.AddMilliseconds(long.Parse(stamp));
            }
            catch (Exception)
            {
                return DateTime.Now;
            }
        }
        #endregion

        #region 获取时间戳
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static string DateTimeToStamp(System.DateTime time, int length = 13)
        {
            long ts = ConvertDateTimeTolong(time);
            return ts.ToString().Substring(0, length);
        }
        #endregion

        #region DateTime时间格式转换为Unix时间戳格式
        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        private static long ConvertDateTimeTolong(DateTime datetime)
        {

            try
            {
                return datetime.Ticks - TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.FindSystemTimeZoneById("China Standard Time")).Ticks;
            }
            catch (Exception)
            {
                return 0;
            }
        }
        #endregion 
    }

 


免责声明!

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



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