BITKit/Packages/Common~/Scripts/Utility/Time.cs

68 lines
2.1 KiB
C#
Raw 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 System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BITKit
{
public static class TimeUtils
{
///<summary>
///2023-02-45 15:02:45:628
///</summary>
public const string dateTimeFormat = "yyyy-MM-dd HH:mm:ss:fff";
/// <summary>
/// 带毫秒的字符转换成时间DateTime格式
/// 可处理格式:[2014-10-10 10:10:10,666 或 2014-10-10 10:10:10 666 或 2014-10-10 10:10:10.666]
/// </summary>
/// 2022-12-30 15:39:48:795
/// 20080501T08:30:52Z"
/// yyyyMMddTHH:mm:ssZ
public static DateTime GetDateTime(string dateTime)
{
try
{
return DateTime.ParseExact(dateTime, dateTimeFormat, null);
}
catch (System.Exception)
{
try
{
return GetDateTime_SCADA(dateTime);
}
catch (System.Exception)
{
Debug.LogWarning($"{dateTime}\n{dateTimeFormat}");
throw;
}
}
}
public static float GetNow(DateTime now = default)
{
now = now == default ? DateTime.Now : now;
float time = 0;
time += now.Hour * 60 * 60;
time += now.Minute * 60;
time += now.Second;
time += now.Millisecond * 0.001f;
return time;
}
public static string GetNowString(DateTime now = default)
{
now = now == default ? DateTime.Now : now;
return now.ToString(dateTimeFormat);
}
static DateTime GetDateTime_SCADA(this string dateTime)
{
string[] strArr = dateTime.Split(new char[] { '-', ' ', ':', ',', '.' });
DateTime dt = new DateTime(int.Parse(strArr[0]),
int.Parse(strArr[1]),
int.Parse(strArr[2]),
int.Parse(strArr[3]),
int.Parse(strArr[4]),
int.Parse(strArr[5]),
int.Parse(strArr[6]));
return dt;
}
}
}