/// <summary>
/// Unix时间戳转换类
/// </summary>
public static class Unix2DateTime
{
/// <summary>
/// 将Unix时间戳转换为DateTime类型时间
/// </summary>
/// <param name="timestamp">long型数字</param>
/// <returns>DateTime</returns>
public static System.DateTime ConvertInt2DateTime(long timestamp)
{
System.DateTime time = System.DateTime.MinValue;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
time = startTime.AddSeconds(timestamp);
return time;
}
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns>long</returns>
public static long ConvertDateTime2Unix(System.DateTime time)
{
double intResult = 0;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
intResult = (time - startTime).TotalSeconds;
return (long)intResult;
}
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns>long</returns>
public static 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 static long GetUnixTimestamp() {
DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的时间戳
long a = (DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000000; //注意这里有时区问题,用now就要减掉8个小时
return a;
}
}