C# DateTime时间格式转换为Unix时间戳格式

时间:2022-04-07 22:51:50

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()
{
DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的时间戳
long a = (DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000; //注意这里有时区问题,用now就要减掉8个小时
return a;
}

 

            //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;
        }