C#计算所给时间与当前时间差
将所给时间字符串(符合格式yyyy-M-d HH:mm:ss,例如“2024-02-26 16:41:30”)转换为DateTime类进行计算
/// <summary>
/// 获取当前时间与time的时间差
/// </summary>
/// <param name=""></param>
/// <returns></returns>
public static void GetDiffTime(string time, Action<TimeSpan> diffAction)
{
DateTime now = DateTime.Now;
string endTime = now.ToString("yyyy-M-d HH:mm:ss.fff");
DateTime startDate = Convert.ToDateTime(time);
DateTime endDate = Convert.ToDateTime(endTime);
TimeSpan timeDiff = endDate - startDate;
diffAction?.Invoke(timeDiff);
}
使用方法:
GetDiffTime("2024-02-26 16:41:30", timeSpan =>
{
if (timeSpan.Hours == 0 && timeSpan.Days == 0)//一小时内
{
if (timeSpan.Minutes == 0)//一分钟内
{
dateText.text = $"刚刚";
}
else
{
dateText.text = $"{timeSpan.Minutes}m";
}
}
else if (timeSpan.Days == 0)//一天内
{
dateText.text = $"{timeSpan.Hours}h";
}
else
{
dateText.text = $"{timeSpan.Days}d";
}
});