using System.Text;
namespace MasstransferCommon.Utils;
public class TimeUtil
{
public static void Sleep(int milliseconds)
{
Thread.Sleep(milliseconds);
}
///
/// 获取当前的时间戳
///
///
public static long Now()
{
return new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
}
public static DateTime ConvertTime(long time)
{
return DateTimeOffset.FromUnixTimeMilliseconds(time).DateTime;
}
///
/// 格式化时间
///
///
///
///
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();
}
}