MasstransferExporter/MasstransferCommon/Utils/TimeUtil.cs

73 lines
1.7 KiB
C#

using System.Text;
namespace MasstransferCommon.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();
}
public static DateTime ConvertTime(long time)
{
return DateTimeOffset.FromUnixTimeMilliseconds(time).DateTime;
}
/// <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 FormatTime(DateTime dateTime, string format = "yyyy-MM-dd HH:mm:ss")
{
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();
}
}