/// <summary>
/// 日期转换成unix时间戳
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static long DateTimeToUnixTimestamp(this DateTime dateTime)
{
var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
var ticks = (dateTime.Ticks - startTime.Ticks);
ticks /= 10000;//除10000调整为13位
return ticks;
}
/// <summary>
/// unix时间戳转换成日期
/// </summary>
/// <param name="timestamp">时间戳(秒)</param>
/// <returns></returns>
public static DateTime UnixTimestampToDateTime(this long timestamp)
{
timestamp *= 10000;//转为ticks
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
TimeSpan timeSpan = new TimeSpan(timestamp);
return startTime.Add(timeSpan);
}
/// 日期转换成unix时间戳
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static long DateTimeToUnixTimestamp(this DateTime dateTime)
{
var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
var ticks = (dateTime.Ticks - startTime.Ticks);
ticks /= 10000;//除10000调整为13位
return ticks;
}
/// <summary>
/// unix时间戳转换成日期
/// </summary>
/// <param name="timestamp">时间戳(秒)</param>
/// <returns></returns>
public static DateTime UnixTimestampToDateTime(this long timestamp)
{
timestamp *= 10000;//转为ticks
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
TimeSpan timeSpan = new TimeSpan(timestamp);
return startTime.Add(timeSpan);
}