【问题标题】:Formatting a period of time格式化一段时间
【发布时间】:2009-12-21 03:44:50
【问题描述】:

在 Java 中,我有一个长整数,表示以毫秒为单位的时间段。时间段可以从几秒到几周不等。我想将此时间段输出为具有适当单位的字符串。

例如 3,000 应输出为“3 秒”,61,200,000 应输出为“17 小时”,1,814,400,000 应输出为“3 周”。

理想情况下,我还可以微调子单元的格式,例如62,580,000 可能会输出为“17 小时 23 分钟”。

是否有任何现有的 Java 类可以处理这个问题?

【问题讨论】:

    标签: java time formatting


    【解决方案1】:

    Joda 库可以为您做到这一点:

    PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder()
     .printZeroAlways()
     .appendYears()
     .appendSuffix(" year", " years")
     .appendSeparator(" and ")
     .printZeroRarely()
     .appendMonths()
     .appendSuffix(" month", " months")
     .toFormatter();
    

    【讨论】:

      【解决方案2】:

      另请参阅 Apache commons 中的 DurationFormatUtils

      【讨论】:

        【解决方案3】:

        查看 joda-time 的 format package

        【讨论】:

          【解决方案4】:
                  //Something like this works good too         
                  long period = ...;
                  StringBuffer sb = new StringBuffer();
                  sb.insert(0, String.valueOf(period % MILLISECS_IN_SEC) + "%20milliseconds");
                  if (period > MILLISECS_IN_SEC - 1)
                      sb.insert(0, String.valueOf(period % MILLISECS_IN_MIN / MILLISECS_IN_SEC) + "%20seconds,%20");
                  if (period > MILLISECS_IN_MIN - 1)
                      sb.insert(0, String.valueOf(period % MILLISECS_IN_HOUR / MILLISECS_IN_MIN) + "%20minutes,%20");
                  if (period > MILLISECS_IN_HOUR - 1)
                      sb.insert(0, String.valueOf(period % MILLISECS_IN_DAY / MILLISECS_IN_HOUR) + "%20hours,%20");
                  if (period > MILLISECS_IN_DAY - 1)
                      sb.insert(0, String.valueOf(period / MILLISECS_IN_DAY) + "%20days,%20");
          
                  return sb.toString();
          

          【讨论】:

          • 这是一种丑陋的做法。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-18
          • 2013-02-02
          • 1970-01-01
          • 1970-01-01
          • 2019-02-17
          • 2022-01-21
          相关资源
          最近更新 更多