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