I have DisplayFor showing a TimeSpan-value (Duration) in this format: 35.04:08:43.2470000 (dd.HH:mm:ss.fffffff).
My goal is a human-readable string "HH:mm" so I followed How to display a TimeSpan in MVC Razor and tried making a DisplayTemplate in ~views/Shared/TimeSpanTemplate.cshtml:
@model TimeSpan
@{
TimeSpan initialValue = Model;
}
@string.Format("{0}:{1}", (initialValue.Days * 24) + initialValue.Hours, initialValue.Minutes)
@Scripts.Render("~/bundles/bootstrap")
This is my model:
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[DisplayName("Varighed")]
public virtual TimeSpan? Duration
{
get {
return SolvedDate.HasValue ? (TimeSpan?)SolvedDate.Value.Subtract(ReportedDate) : null; }
}
This is my view:
<td>
@Html.DisplayFor(modelItem => item.Ticket.Duration)
</td>
I get this compile formatexception error:
Input string was not in a correct format. --> "@Html.DisplayFor(modelItem => item.Ticket.Duration)"
System.FormatException was unhandled by user code
HResult=-2146233033 Message=Input string was not in a correct format. Source=mscorlib
I have successfully created DateTime-templates for EditViews, but I cant seem to get around this problem on DisplayFor with TimeSpan-types.
I dont have the faintest idea what I am doing, so any clues are appreciated! :) Thanks in advance!
This is not a direct answer to solve this problem, but I think it would be better to use the Humanizer library.
You would be able to do the following:
See here: https://github.com/Humanizr/Humanizer#humanize-timespan