在c#中将十进制值转换为时间格式

本文关键字:转换 时间 格式 十进制 | 更新日期: 2023-09-27 18:06:37

我目前正在从数据库中获取2个日期,并找到它们之间的差异。我在我的视图页面中显示总和的值,但它目前显示为十进制。例如,生成的值之一是1585.913,但我希望它是HH:MM:SS格式。

当前显示十进制值的代码如下:

h2控制器

public ActionResult Execution(int id = 0)
    {
        Execution execution = db.Executions.Find(id);
        if (execution == null)
        {
            return HttpNotFound();
        }
        ViewBag.ExecutionSeconds = (execution.End - execution.Start).TotalSeconds;
        return View(execution);
    }
<<h2>视图/h2>
@ViewBag.ExecutionSeconds

我必须对这段代码进行哪些更改才能使其以HH:MM:SS格式显示值?

在c#中将十进制值转换为时间格式

您可以使用.ToString()方法格式化您的TimeSpan。例如:

(execution.End - execution.Start).ToString(@"dd'.hh':mm':ss");

更多信息:

https://msdn.microsoft.com/en-us/library/ee372287 (v = vs.110) . aspx

两个日期相减返回TimeSpan类型的结构

(execution.End - execution.Start);// returns TimeSpan
(execution.End - execution.Start).ToString(@"hh':mm':ss"); // format it

时间间隔格式

如果您的时间大于24小时(如@juharr指出的),您可以使用

string.Format("{0}:{1}:{2}", (int)time.TotalHours, time.Minutes, time.Seconds);

或通过将格式化字符串替换为@"dd'.hh':mm':ss"

来包含天数

我将为TimeSpan添加一个扩展,因为这种格式经常发生(从这里复制):

public static string ToReadableString(this TimeSpan span)
{
    string formatted = string.Format("{0}{1}{2}{3}",
        span.Duration().Days > 0 ? string.Format("{0:0} day{1}, ", span.Days, span.Days == 1 ? String.Empty : "s") : string.Empty,
        span.Duration().Hours > 0 ? string.Format("{0:0} hour{1}, ", span.Hours, span.Hours == 1 ? String.Empty : "s") : string.Empty,
        span.Duration().Minutes > 0 ? string.Format("{0:0} minute{1}, ", span.Minutes, span.Minutes == 1 ? String.Empty : "s") : string.Empty,
        span.Duration().Seconds > 0 ? string.Format("{0:0} second{1}", span.Seconds, span.Seconds == 1 ? String.Empty : "s") : string.Empty);
    if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);
    if (string.IsNullOrEmpty(formatted)) formatted = "0 seconds";
    return formatted;
}

您需要将返回execution.End - execution.Start表达式的TimeSpan格式化为@"hh':mm':ss"格式,如;

TimeSpan ts = execution.End - execution.Start;
string seconds = ts.ToString(@"hh':mm':ss"); // 00:26:25

顺便说一下,在自定义TimeSpan格式中没有MM说明符,它应该是小写的mm说明符。