TestCodeStructure/Assets/Scripts/Utils/TimeTool.cs

89 lines
3.0 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using UnityEngine;
public class TimeTool
{
public static TimeSpan GetNowTimeSpan()
{
return DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
}
public static TimeSpan GetGameRunTimeSpan()
{
return GetGameRunTimeSpan((int)Time.realtimeSinceStartup);
}
public static TimeSpan GetGameRunTimeSpan(int runTime)
{
int hour = runTime / 3600;
int minute = (runTime - (hour * 3600)) / 60;
int second = runTime - (hour * 3600) - (minute * 60);
#if UNITY_EDITOR
Debug.Log($"get TimeSpan hour : {hour} minute : {minute} second : {second}");
#endif
return new TimeSpan(hour, minute, second);
}
/// <summary>
/// 获取当前时间戳
/// </summary>
/// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.bool bflag = true</param>
/// <returns></returns>
public static long GetTimeStamp(bool notMill)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
if (notMill)
return Convert.ToInt64(ts.TotalSeconds);
else
return Convert.ToInt64(ts.TotalMilliseconds);
}
public static DateTime GetCurrDateTime(long timeStamp)
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
return startTime.AddTicks(timeStamp * 10000000);
}
/// <summary>
/// 时间戳转化为本地时间
/// </summary>
/// <param name="timeStamp"></param>
/// <param name="notMill"></param>
/// <returns></returns>
public static string GetFormatTime(long timeStamp, bool notMill)
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
DateTime dataTime = startTime.AddTicks(timeStamp * 10000000);
if (notMill)
{
return dataTime.ToString("yyyy-MM-dd HH:mm:ss");
}
else
{
return dataTime.ToString("yyyy-MM-dd HH:mm:ss fff");
}
}
public static int GetCurrDayOfYear()
{
return DateTime.Today.DayOfYear;
}
/// <summary>
/// 获取当前是一年当中的第几周
/// </summary>
/// <returns></returns>
public static int GetCurrWeekOfYear()
{
//一.找到第一周的最后一天先获取1月1日是星期几从而得知第一周周末是几
int firstWeekend = 7 - Convert.ToInt32(DateTime.Parse(DateTime.Today.Year + "-1-1").DayOfWeek);
//二.获取今天是一年当中的第几天
int currentDay = DateTime.Today.DayOfYear;
//三.(今天 减去 第一周周末)/7 等于 距第一周有多少周 再加上第一周的1 就是今天是今年的第几周了
// 刚好考虑了惟一的特殊情况就是今天刚好在第一周内那么距第一周就是0 再加上第一周的1 最后还是1
return Convert.ToInt32(Math.Ceiling((currentDay - firstWeekend) / 7.0)) + 1;
}
}