处理Unix时间戳的工具类

This commit is contained in:
jackfiled 2023-02-10 16:16:28 +08:00
parent 6cac80fe17
commit d288e05988
3 changed files with 40 additions and 0 deletions

3
Assets/Utils.meta Normal file
View File

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: cdc8c485ff3349409e3bc22fa04a148e
timeCreated: 1676013511

View File

@ -0,0 +1,34 @@
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);
}
}
}

View File

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: aed416aa0d4d4f04a91c72c39d052972
timeCreated: 1676013530