0

I have a Razor view with

@Html.DisplayFor(modelItem => item.TotalTime)

and the type of TotalTime is TimeSpan.

It works great problem is we have now found a few cases where the TotalTime goes over 24hrs so it shows as 1.01:00:00 (1day, 1Hr, 00Mins, 00 Secs). so the value is still correct but I need it to display as 25:00:00 (25Hrs, 00Mins, 00Secs).

I could change the model to a string but it's used in various places including formulas etc so it's not a simple task, hence I am looking to just change the display of the value.

I have looked around for a Data Annotation for the DisplayFor but not found one that will work so I am open to suggestions

Thanks

Cliff.

Clifford Agius
  • 181
  • 4
  • 15
  • 1
    Similar situation for a Boolean http://stackoverflow.com/questions/6870683/how-do-i-override-displayfor-boolean – Jim Crandall Feb 12 '15 at 20:21
  • 2
    Have you tried the [TotalHours](https://msdn.microsoft.com/en-us/library/system.timespan_properties(v=vs.110).aspx) attribute `item.TotalTime.TotalHours`? – Jasen Feb 12 '15 at 20:22
  • And the `DisplayFor` helper is trying to be "helpful" and producing that formatted string. You'll need to write your own or not use it at all. – Jasen Feb 12 '15 at 20:29

2 Answers2

1

You'll need to take the separate parts calculate the hours from the Days and Hours parts.

Here's a helper extension:

public static HtmlString TimeSpanString(this HtmlHelper helper, TimeSpan val)
{
    double days = val.Days;
    double hours = val.Hours + (days * 24);
    double minutes = val.Minutes;
    double seconds = val.Seconds;
    var formattedString = String.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);

    return new HtmlString("<span>" + formattedString + "</span>");
}

Usage:

@Html.TimeSpanString(item.TotalTime)
Jasen
  • 14,030
  • 3
  • 51
  • 68
1

Ok so as suggested by Jim Crandell above I have added a Display Template like so:

Views\Shared\DisplayTemplates\TimeSpan.cshtml (I created a new folder and a partial view)

Inside this new partial view I added:

@model TimeSpan
@string.Format("{0}:{1}:{2}",(Model.Days *24) + Model.Hours, Model.Minutes, Model.Seconds)

And it works Yay thanks guys...

smrzjose
  • 33
  • 1
  • 6
Clifford Agius
  • 181
  • 4
  • 15