Question

I'm doing the follwing:

//TimeSpan rebateTime
//int percentage
string text = string.Format(
    CultureInfo.CurrentCulture, 
    "Rebate {0}% during {1:hh} h {1:mm} min", 
    percentage, 
    rebateTime;

On my dev pc text contains:

Rebate 32% during 05 h 00 min

On my dev test server text contains:

Rebate 32% during 05 h 00 min

On my the shared test server text contains:

Rebate 32% during 05:00:00 h 05:00:00 min

How can this be possible at all?

No correct solution

OTHER TIPS

I reproduced you error here.

This format only works from .NET 4. Probably .NET 4 isn't installed in your shared server.

Look at section Formatting a TimeSpan Value in TimeSpan Structure MSDN docs.

To check this, create a simple console project:

    static void Main(string[] args)
    {
        Console.WriteLine(String.Format(CultureInfo.CurrentCulture, "Rebate {0}% during {1:hh} h {1:mm} min", 0.15, new TimeSpan(DateTime.Now.Ticks)));
        Console.ReadKey();
    }

Outputs:

.NET 4

"Rebate 0.15% during 11 h e 47 min"

.NET 3.5

"Rebate 0,15% during 735275.11:48:48.7362198 h 735275.11:48:48.7362198 min"

As others have pointed out, TimeSpan didn't have custom formating before .NET 4. However, the alternate solution isn't complicated at all:

string.Format
(
    "Rebate {0}% during {1:##} h {2:##} min", 
    percentage, 
    rebateTime.TotalHours, 
    rebateTime.Minutes
);

As it happens I had the exact same issue today. I fixed it by using an extension method:

    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:00} hour{1}, ", span.Hours, span.Hours == 1 ? String.Empty : "s") : string.Empty,
            span.Duration().Minutes > 0 ? string.Format("{0:00} minute{1}, ", span.Minutes, span.Minutes == 1 ? String.Empty : "s") : string.Empty,
            span.Duration().Seconds > 0 ? string.Format("{0:00} 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;
    }

When it's used on a timespan you will get the time in the following format (x days x hours x minutes x seconds) whenever something isn't available it will be hidden.

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