C#字符串格式表示小数和小时的小时和分钟

时间:2011-05-01 23:56:27

标签: c# .net string-formatting

是否有一个简单的字符串格式,它将采用小数表示小时和小时的分数,并将其显示为小时和分钟?

例如:5.5格式化显示5小时30分钟。

我很乐意自己编写代码,但是如果可用,则更愿意使用现有功能

3 个答案:

答案 0 :(得分:27)

decimal t = 5.5M;
Console.WriteLine(TimeSpan.FromHours((double)t).ToString());

那将给你“05:30:00”,这是非常接近。然后,您可以将其格式化为所需的结果:

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

请注意,从十进制到双倍的转换可能会导致精度损失,但我不认为它会在分钟范围内显而易见。对类型系统有类似Skeet理解的人可能会在这里发声。

答案 1 :(得分:1)

我根据Matt的评论为此写了一些小助手方法。对于某人来说,保存你自己写作可能会有用。

/// <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;
}

答案 2 :(得分:0)

如果您的时间超过24小时,则必须考虑TimeSpan类具有Days属性,并且Hours属性将循环。这样的事情可以防止超过24小时的任何错误:

 var tsExample = TimeSpan.FromHours(timeInDecimal);
 var result = $"{tsExample.Hours + (tsExample.Days * 24):00}:{tsExample.Minutes:00}";