TimeSpan for a localized string in C #

Is there an easy way (possibly built into the solution) to convert TimeSpanto a localized string? For example, it new TimeSpan(3, 5, 0);will be converted to 3 hours, 5minutes(Polish only).

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 it gets complicated if I want to have the correct grammar.

+3
source share
3 answers

I do not think that's 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");
}
+2
source

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

Unfortunately, there is no standard way to do such a thing.

, , , ...: -\

, , , .

+2

, :

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;
    }
+1

Source: https://habr.com/ru/post/1737861/


All Articles