【问题标题】:C#: Best way to achieve a nicely formatted time string?C#:实现格式良好的时间字符串的最佳方法?
【发布时间】:2017-07-26 17:01:10
【问题描述】:

我正在写这个问题,因为我正在寻求最好的方法来做到这一点。我的程序中有很多这样的,我想创建一个方法将包含一秒计时器的 Int32 转换为格式良好的字符串。

例如,如果我的计时器 int 是在,让我们说一个像 16429 这样的随机数 应该是:

4 hours, 32 minutes and 9 seconds

如果是 600,那就是:

10 minutes

如果是60,那就是

1 minute

如果是172801,那就是

2 days and 1 second

如果是32,那就是

32 seconds

我希望“分钟”、“秒”和“天”等每个单词末尾的“s”仅在不等于 1 时放置 S,因此实际上不需要发音正确。我也只希望在需要时添加天数和小时数以及其他内容,因此如果计时器以秒为单位低于 1 天,它只会显示小时、分钟和秒,或需要的内容。

实现这样的目标的最佳方法是什么?我在下面有这个功能,但它非常混乱,最多只能达到几分钟和几秒钟,而不是几小时或几天:

public static string GetConvertedTime(int timer)
{
    int Minutes = timer / 60;
    int Seconds = timer - Minutes * 60;

    if (timer < 60)
    {
        string secs = (Seconds != 1) ? "s" : "";
        return "" + timer + " second" + secs;
    }

    else
    {
        if (Seconds < 1)
        {
            string mins = (Minutes != 1) ? "s" : "";
            return "" + Minutes + " minute" + mins;
        }
        else
        {
            string mins = (Minutes != 1) ? "s" : "";
            string secs = (Seconds != 1) ? "s" : "";
            return "" + Minutes + " minute" + mins + " and " + Seconds + " second" + secs;
        }
    }
}

最好的方法是什么?

【问题讨论】:

    标签: c# .net datetime system.timers.timer


    【解决方案1】:

    “最佳方式”非常主观。 DRY 通常是最好的,考虑到本地化和非常规复数形式通常是最好的,保持简短和活泼通常是最好的:

    public static string FriendlyDuration(int seconds) {
        int[] divisors = { 60 * 60 * 24, 60 * 60, 60 , 1};
        string[] language = { ", ", " and ", "days", "day", "hours", "hour", "minutes", "minute", "seconds", "second"};
        var parts = new List<string>();
        for (int part = 0; part < divisors.Length; ++part) {
            int count = seconds / divisors[part];
            if (count == 0) continue;
            string unit = language[part*2 + (count == 1 ? 3 : 2)];
            parts.Add(string.Format("{0} {1}", count, unit));
            seconds -= count * divisors[part];
        }
        var result = string.Join(language[0], parts.ToArray());
        if (parts.Count > 1) {
            var ix = result.LastIndexOf(language[0]);
            result = result.Substring(0, ix) + language[1] + result.Substring(ix + language[0].Length);
        }
        return result;
    }
    

    【讨论】:

    • 这看起来像是我希望在多年经验后我会考虑编写的那种代码,+1
    • 留给 Hans Passant 写这样一个令人难以置信的例子。
    【解决方案2】:

    可能我能想到的最好方法是像这样使用TimeSpan

    var time = new TimeSpan(0, 0, timer);
    var s = "s";
    return $"{time.Days} day{(time.Days != 1 ? s : String.Empty)}, {time.Hours} hour{(time.Hours != 1 ? s : String.Empty)}, {time.Minutes} minute{(time.Minutes != 1 ? s : String.Empty)}, and {time.Seconds} second{(time.Seconds != 1 ? s : String.Empty)}";
    

    如果需要隐藏空前导值:

    var sb = new StringBuilder();
    var s = "s";
    var time = new TimeSpan(0, 0, timer);
    var continuation = false;
    if (time.Days > 0)
    {
        sb.Append($"{time.Days} day{(time.Days != 1 ? s : String.Empty)}, ");
        continuation = true;
    }
    if (time.Hours > 0 || continuation)
    {
        sb.Append($"{time.Hours} hour{(time.Hours != 1 ? s : String.Empty)}, ");
        continuation = true;
    }
    if (time.Minutes > 0 || continuation)
    {
        sb.Append($"{time.Minutes} minute{(time.Minutes != 1 ? s : String.Empty)}{(continuation ? "," : String.Empty)} ");
        continuation = true;
    }
    if (continuation) sb.Append("and ");
    
    sb.Append($"{time.Seconds} second{(time.Seconds != 1 ? s : String.Empty)}");
    return sb.ToString();
    

    【讨论】:

      【解决方案3】:

      你可以试试这个名为Humanizer的库

      【讨论】:

      • 仅链接的答案不是很有用
      • @Buhbuh,当然是,你希望答案是什么,来自 github 的完整源代码?知道产品的存在是有用的,有一个链接就更好了
      • @pm100 我认为一个合理的期望是展示如何使用所述库完成任务。 “试试这个库”更多的是评论而不是答案。
      • @pm100 而在How do I write a good answer? 下,我们有一个部分专门针对这些类型的答案。 鼓励使用指向外部资源的链接,但请在链接周围添加上下文,以便您的其他用户了解它是什么以及它存在的原因。始终引用重要链接中最相关的部分,以防目标站点无法访问或永久离线。
      猜你喜欢
      • 2010-10-07
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 2012-03-19
      • 2012-07-09
      相关资源
      最近更新 更多