1

是否有以人们说话的方式打印时间段的库?我的意思是,它应该将以精确的时间单位给出的时间段转换为具有一定程度不精确性的“口述”时间段,例如:

  • 360 天 -> “1 年”,
  • 32 天 -> "1 个月",
  • 385 天 -> 1 年 1 个月"

JodaTime 通过切断所有“零”持续时间部分来解决这个问题,但它甚至不能将几天变成几个月:

    PeriodFormatterBuilder builder = new PeriodFormatterBuilder().
        appendYears().appendSuffix(" year(s) ").
        appendMonths().appendSuffix(" month(s) ").
        appendDays().appendSuffix(" day(s)");


    MutablePeriod almostOneYear = new MutablePeriod(0, 0, 0, 360, 0, 0, 0, 0);

    StringBuffer durationInWords = new StringBuffer();
    builder.toPrinter().printTo(durationInWords, almostOneYear, Locale.ENGLISH);

    System.out.println(durationInWords.toString());

产生“360 天”,甚至不是“n 个月 m 天”(n,m — 取决于什么是“标准”年)。也许我用错了?

4

1 回答 1

1

不要认为有一个图书馆。为什么不创建一个简单的函数来为你做这件事,比如:

  public static String toHumanFormat(int totalDays){
    int years = totalDays / 356;
    int months = (totalDays % 356) / 30;
    int days = totalDays % 356 % 30;
    return MessageFormat.format("{0,choice,0#|1#1 year|1<{0} years} " +
            "{1,choice,0#|1#1 month|1<{1} months} " +
            "{2,choice,0#|1#1 day|1<{2} days}",
            years, months, days).trim();
  }
于 2012-06-01T15:01:12.670 回答