1

Joda Time のように、期間を英語や他の言語にフォーマットしたいと思います。

ただし、これを処理するコードを記述せずに、最も重要なフィールドを 1 つまたは 2 つ (たとえば、「2 年と 3 か月」または「5 日」) リストする簡単な方法が必要です。Joda Time の問題は、コードを書かない限り、「2 年 3 か月 5 日」のような出力が得られることです。

私がやりたいことを正確に行うPretty Timeのようなライブラリがありますが、「3か月前」のように、現在との比較のみを目的としています。欲しいのは「3ヶ月」です。

Pretty Time のように動作するライブラリが存在するはずですが、一般的な期間は必要ですか?

私は特に Grails/Groovy を使用していますが、単純な Java ソリューションも同様に受け入れられます。

4

1 に答える 1

1

Joda Time を使って少しのコードを書けないのはなぜですか? 私はあなたと同様の問題を抱えていましたが、次のようなユーティリティメソッドで解決しました:

DateTime dt = new DateTime(); // Now
DateTime plusDuration = dt.plus(new Duration(110376000000L)); // Now plus three years and a half

// Define and calculate the interval of time
Interval interval = new Interval(dt.getMillis(), plusDuration.getMillis());

// Parse the interval to period using the proper PeriodType
Period period = interval.toPeriod(PeriodType.yearMonthDayTime());

// Define the period formatter for pretty printing the period
PeriodFormatter pf = new PeriodFormatterBuilder()
        .appendYears().appendSuffix("y ", "y ")
        .appendMonths().appendSuffix("m", "m ").appendDays()
        .appendSuffix("d ", "d ").appendHours()
        .appendSuffix("h ", "h ").appendMinutes()
        .appendSuffix("m ", "m ").appendSeconds()
        .appendSuffix("s ", "s ").toFormatter();

// Print the period using the previously created period formatter
System.out.println(pf.print(period).trim());

お探しのものではないかもしれませんが、参考になれば幸いです。

よろしく。

于 2012-09-25T08:48:11.733 に答える