Dispenser/DispenserCommon/Utils/TimeUtil.cs

88 lines
2.2 KiB
C#

using System.Text;
namespace DispenserCommon.Utils;
public class TimeUtil
{
public static void Sleep(int milliseconds)
{
Thread.Sleep(milliseconds);
}
/// <summary>
/// 获取当前的时间戳
/// </summary>
/// <returns></returns>
public static long Now()
{
return new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
}
/// <summary>
/// 获取当前的时间,格式化为目标格式
/// </summary>
/// <param name="format"></param>
/// <returns></returns>
public static string GetNowTime(string format = "yyyy-MM-dd HH:mm:ss")
{
return DateTime.Now.ToString(format);
}
/// <summary>
/// 格式化时间
/// </summary>
/// <param name="time"></param>
/// <param name="format"></param>
/// <returns></returns>
public static string FormatTime(long time, string format = "yyyy-MM-dd HH:mm:ss")
{
var dateTime = DateTimeOffset.FromUnixTimeMilliseconds(time).DateTime;
return dateTime.ToString(format);
}
public static string ToTimeSpan(long time)
{
// 使用TimeSpan.FromMilliseconds来创建TimeSpan对象
var timeSpan = TimeSpan.FromMilliseconds(time);
// 获取小时、分钟和秒
var hours = timeSpan.Hours;
var minutes = timeSpan.Minutes;
var seconds = timeSpan.Seconds;
var sb = new StringBuilder();
if (hours > 0)
{
sb.Append(hours).Append("小时");
}
if (minutes > 0)
{
sb.Append(minutes).Append('分');
}
if (seconds > 0)
{
sb.Append(seconds).Append('秒');
}
return sb.ToString();
}
/// <summary>
/// 将时间戳转为DateTime对象
/// </summary>
/// <param name="timestamp"></param>
/// <returns></returns>
public static DateTime TimeStampToDateTime(long timestamp)
{
var dateTimeOffset = (timestamp + "").Length == 10
? DateTimeOffset.FromUnixTimeSeconds(timestamp)
: DateTimeOffset.FromUnixTimeMilliseconds(timestamp);
return dateTimeOffset.DateTime;
}
}