using System;
namespace Utils
{
public class DateTimeUtil
{
private static readonly DateTime UtcStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
///
/// 转换为Unix时间戳
///
/// 需要转换的时间
/// Unix时间戳
public static long ToUnixTimeStamp(DateTime dateTime)
{
var utcTime = dateTime.ToUniversalTime();
var timeSpan = utcTime - UtcStartTime;
return Convert.ToInt64(timeSpan.TotalSeconds);
}
///
/// 从Unix时间戳转换为日期时间对象
///
/// Unix时间戳
/// Unix时间戳代表的日期时间对象
public static DateTime FromUnixTimeStamp(long timeStamp)
{
var utcTime = UtcStartTime.AddSeconds(timeStamp);
return TimeZoneInfo.ConvertTimeFromUtc(utcTime, TimeZoneInfo.Local);
}
}
}