天天看點

C# DateTime時間格式轉換為Unix時間戳格式

double ntime=dateTimeToUnixTimestamp(DateTime.Now);

long g1 = GetUnixTimestamp();

long g2 = ConvertDateTime2Long(DateTime.Now);

public double dateTimeToUnixTimestamp(DateTime datetime)

{

return (datetime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds/10000;

}

      string date = DateTime.Now.AddYears(-20).ToString("yyyy-MM-dd HH:mm:ss");

1995-11-05 20:15:37

/// <summary>

/// 将c# DateTime時間格式轉換為Unix時間戳格式

/// </summary>

/// <param name="time">時間</param>

/// <returns>long</returns>

public long ConvertDateTime2Long(System.DateTime time)

DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的時間戳

long a = (time.ToUniversalTime().Ticks - timeStamp.Ticks) / 10000000; //注意這裡有時區問題,用now就要減掉8個小時

return a;

//擷取目前時間的時間戳

public long GetUnixTimestamp()

long a = (DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000; //注意這裡有時區問題,用now就要減掉8個小時

//1416270102
            long temp = GetUnixTimestamp();
            DateTime tamp = GetTime(Convert.ToString(temp));        
        

        /// <summary>
        /// c# to unix
        /// </summary>
        /// <returns></returns>
        public static long GetUnixTimestamp()
        {
            DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的時間戳
            long a = (DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000000; //注意這裡有時區問題,用now就要減掉8個小時
            return a;
        }
        /// <summary>
        /// unix to c#
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = new DateTime(1970, 1, 1); //得到1970年的時間戳
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime temp=dtStart.Add(toNow);
            System.TimeSpan duration = new System.TimeSpan(0, 8, 0, 0);
            System.DateTime answer = temp.Add(duration);
            return answer;
        }