开发者

TimeSpan to Localized String in C#

Is there an easy way (maybe built in solution) to convert TimeSpan to localized string? For example new TimeSpan(3, 5, 0); would be converted to 3 hours, 5minutes (just in polish language).

I can of course create my own extension:

    public static string ConvertToReadable(this TimeSpan timeSpan) {
        int hours = timeSpan.Hours;
        int minutes = timeSpan.Minutes;
        int days = timeSpan.Days;
        if (days > 0) {
            return days + " dni " + hours + " godzin " + minutes + " minut";
   开发者_开发知识库     } else {
            return hours + " godzin " + minutes + " minut";
        }
    }

But this gets complicated if i want to have proper grammar involved.


The easiest way to do this is to put the format string in a localized resource, and translate appropriately for each supported language.

Unfortunately there's no standard way to do such thing.

Nobody seems to agree in what should be the proper way.... :-\

And people like us that write software for multiple languages suffer.


I do not think this is possible. What you can do is something like this:

public static string ConvertToReadable(this TimeSpan timeSpan) { 
    return string.Format("{0} {1} {2} {3} {4} {5}",
        timeSpan.Days, (timeSpan.Days > 1 || timeSpan.Days == 0) ? "days" : "day",
        timeSpan.Hours, (timeSpan.Hours > 1 || timeSpan.Hours == 0) ? "hours" : "hour",
        timeSpan.Minutes, (timeSpan.Minutes > 1 || timeSpan.Minutes == 0) ? "minutes" : "minute");
}


Here's the code that I've cooked out:

public static string ConvertToReadable(this TimeSpan timeSpan) {
        int hours = timeSpan.Hours;
        int minutes = timeSpan.Minutes;
        int days = timeSpan.Days;
        string hoursType;
        string minutesType;
        string daysType;
        switch (minutes) {
            case 1:
                minutesType = "minuta";
                break;
            case 2:
            case 3:
            case 4:
                minutesType = "minuty";
                break;
            default:
                minutesType = "minut";
                break;
        }
        switch (hours) {
            case 1:
                hoursType = "godzina";
                break;
            case 2:
            case 3:
            case 4:
                hoursType = "godziny";
                break;
            default:
                hoursType = "godzin";
                break;
        }
        switch (days) {
            case 1:
                daysType = "dzień";
                break;
            default:
                daysType = "dni";
                break;
        }


        if (days > 0) {
            return days + " " + daysType + " " + hours + " " + hoursType + " " + minutes + " " + minutesType;
        }
        return hours + " " + hoursType + " " + minutes + " " + minutesType;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜