C#時間戳與時間相互轉換

代碼:ide

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataSync.Utils
{
    /// <summary>
    /// 時間工具類
    /// </summary>
    public class DateTimeUtil
    {
        private static DateTime _dtStart = new DateTime(1970, 1, 1, 8, 0, 0);

        /// <summary> 
        /// 獲取時間戳 
        /// </summary>  
        public static string GetTimeStamp(DateTime dateTime)
        {
            return Convert.ToInt64(dateTime.Subtract(_dtStart).TotalMilliseconds).ToString();
        }

        /// <summary> 
        /// 根據時間戳獲取時間 
        /// </summary>  
        public static DateTime TimeStampToDateTime(string timeStamp)
        {
            return _dtStart.AddMilliseconds(Convert.ToInt64(timeStamp));
        }

        /// <summary> 
        /// 根據時間戳獲取時間 
        /// </summary>  
        public static DateTime TimeStampToDateTime(long timeStamp)
        {
            if (timeStamp > 0)
            {
                return _dtStart.AddMilliseconds(timeStamp);
            }
            return DateTime.MinValue;
        }
    }
}
View Code
相關文章
相關標籤/搜索