30 days hath September,
April, June and November,
All the rest have 31,
Excepting February alone
(And that has 28 days clear,
With 29 in each leap year).
この情報をアナグラム的に取得できますか? (もちろん、詩のことではありません)
月の値を表すオブジェクトがある場合DateTime
、それは非常に簡単です。dayOfMonth
そのオブジェクトからプロパティを取得し、プロパティDateTime
の最大値を取得します。サンプル関数を次に示します。
public static int daysOfMonth(int year, int month) {
DateTime dateTime = new DateTime(year, month, 14, 12, 0, 0, 000);
return dateTime.dayOfMonth().getMaximumValue();
}
はい、それほどきれいではありませんが:
import org.joda.time.*;
import org.joda.time.chrono.*;
import org.joda.time.field.*;
public class Test {
public static void main(String[] args) {
GregorianChronology calendar = GregorianChronology.getInstance();
DateTimeField field = calendar.dayOfMonth();
for (int i = 1; i < 12; i++) {
LocalDate date = new LocalDate(2010, i, 1, calendar);
System.out.println(field.getMaximumValue(date));
}
}
}
12 か月あり、2010 年に関心があるという仮定をハードコーディングしたことに注意してください。ただし、グレゴリオ暦の年表を明示的に選択しました。もちろん、他の年表では異なる答えが得られます。(そして、「12 か月」ループも有効な仮定ではありません...)
値を取得するためにaLocalDate
ではなく aを使用DateTime
して、値がタイム ゾーンに依存しないことを強調しました (しかしかすかに :)。
これは見た目ほど単純ではありません。ある年表を使用して を構築するとどうなるかはわかりませんがLocalDate
、別の年表でフィールドの最大値を求めます。Joda Timeについてある程度知っているので、何が起こるかについていくつかのアイデアがありますが、それはおそらく良い考えではありません:)
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, yourMonth);
cal.set(Calendar.YEAR, yourYear);
cal.getActualMaximum(Calendar.DAY_OF_MONTH); // <-- the result!
別の単純な関数を次に示します。
int daysOfMonth(DateTime dt) {
int month = dt.getMonthOfYear();
int month2 = month;
int days = dt.getDay();
DateTime dt2 = dt;
while (month == month2 ) {
days++;
dt2.addDays(1);
month2 = dt2.getMonthOfYear();
}
return (days - 1);
}