C# String Format for hours and minutes from decimal

前端 未结 3 1127
盖世英雄少女心
盖世英雄少女心 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.

    /// <summary>Converts a decimal e.g. 1.5 to 1 hour 30 minutes</summary>
    /// <param name="duration">The time to convert as a double</param>
    /// <returns>
    ///     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
    /// </returns>
    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;
    }
    
    /// <summary>Pluralise hour or minutes based on the amount of time</summary>
    /// <param name="num">The number of hours or minutes</param>
    /// <param name="word">The word to pluralise e.g. "hour" or "minute"</param>
    /// <returns> Returns correct English pluralisation e.g. 3 hours, 1 minute, 0 minutes</returns>
    public String pluraliseTime(int num, String word)
    {
        return (num == 0 || num > 1) ? word + "s" : word;
    }
    
    0 讨论(0)
  • 2020-12-17 15:45

    If you have time that can be more than 24 hours, you have to consider that the TimeSpan class has a Days property, and the Hours property will cycle. Something like this will prevent any error from time with more than 24 hours:

     var tsExample = TimeSpan.FromHours(timeInDecimal);
     var result = $"{tsExample.Hours + (tsExample.Days * 24):00}:{tsExample.Minutes:00}";
    
    0 讨论(0)
  • 2020-12-17 15:56
    decimal t = 5.5M;
    Console.WriteLine(TimeSpan.FromHours((double)t).ToString());
    

    That'll give you "05:30:00" which is pretty close. You could then format that to your desired result:

    var ts = TimeSpan.FromHours((double)t);
    Console.WriteLine("{0} hrs {1} minutes", ts.Hours, ts.Minutes);
    

    Note that there's a potential for loss of accuracy in the conversion from decimal to double, but I don't think it would be noticeable on the minute scale. Someone with a Skeet-like understanding of the type system might be able to chime in here.

    0 讨论(0)
提交回复
热议问题