C# String Format for hours and minutes from decimal

前端 未结 3 1130
盖世英雄少女心
盖世英雄少女心 2020-12-17 15:09

Is there a simple string format that will take a decimal representing hours and fractions of hours and show it as hours and minutes?

For example : 5.5 formatted to d

3条回答
  •  春和景丽
    2020-12-17 15:37

    I wrote a few small helper methods for this based on Matt's comment. Might be useful for someone to save you writing it yourself.

    /// Converts a decimal e.g. 1.5 to 1 hour 30 minutes
    /// The time to convert as a double
    /// 
    ///     Returns a string in format:
    ///     x hours x minutes
    ///     x hours (if there's no minutes)
    ///     x minutes (if there's no hours)
    ///     Will also pluralise the words if required e.g. 1 hour or 3 hours
    /// 
    public String convertDecimalToHoursMinutes(double time)
    {
        TimeSpan timespan = TimeSpan.FromHours(time);
        int hours = timespan.Hours;
        int mins = timespan.Minutes;
    
        // Convert to hours and minutes
        String hourString = (hours > 0) ? string.Format("{0} " + pluraliseTime(hours, "hour"), hours) : "";
        String minString = (mins > 0) ? string.Format("{0} " + pluraliseTime(mins, "minute"), mins) : "";
    
        // Add a space between the hours and minutes if necessary
        return (hours > 0 && mins > 0) ? hourString + " " + minString : hourString + minString;
    }
    
    /// Pluralise hour or minutes based on the amount of time
    /// The number of hours or minutes
    /// The word to pluralise e.g. "hour" or "minute"
    ///  Returns correct English pluralisation e.g. 3 hours, 1 minute, 0 minutes
    public String pluraliseTime(int num, String word)
    {
        return (num == 0 || num > 1) ? word + "s" : word;
    }
    

提交回复
热议问题