Question

I need to create a display template in ASP.NET MVC 3 that will display a Timespan, showing only the properties with values set. Here are some examples to show what I mean:

Timespan: 1 day, 2 hours, 3 minutes
Required display: "1 day, 2 hours, 3 minutes"

Timespan: 0 days, 2 hours, 1 minute
Required display: "2 hours, 1 minute"

Timespan: 0 days, 5 hours, 0 minutes
Required display: "5 hours"

So as you can see, I need to show only the non-zero values; but I don't know how... apart from an inelegant solution with many if statements. I want to find a better way.

Here is my current code:

@model TimeSpan

@if (Model.Days > 0)
{
    @Model.Days if (Model.Days > 1)
                {<text>days</text>}
                else
                { <text>day</text>}
}

@if (Model.Hours > 0)
{
    if (Model.Days > 0)
    {
        @:, 
    }
    @Model.Hours if (Model.Hours > 1)
                 {<text>hours</text>}
                 else
                 { <text>hour</text>}
}

@if (Model.Minutes > 0)
{
    if (Model.Days > 0 || Model.Hours > 0)
    {
        @:, 
    }
    @Model.Minutes if (Model.Minutes > 1)
                   {<text>minutes</text>}
                   else
                   { <text>minute</text>}
}
Was it helpful?

Solution

You might refactor a bit (untested, not sure if @functions will work in a template file, but... why wouldn't it ?)

@model TimeSpan

@functions{
    public string FormatElement(int value, string text){
        if (value == 0) return string.Empty;
        if (value > 1) text +="s";
        return string.Format("{0} {1}", value, text);
    }
}

@string.Join(", ",  new[]{
                        FormatElement(Model.Days, "day"), 
                        FormatElement(Model.Hours, "hour"), 
                        FormatElement(Model.Minutes, "minute")
                    }
                   .Where(m => m != string.Empty));

OTHER TIPS

As @Serv commented this was answered at How do I convert a TimeSpan to a formatted string? by Peter.

Please go there to see his solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top