Java 8新特性日付API

4635 ワード

Java 8はパッケージjava.timeの下には、新しいタイム日付APIのセットが含まれています.次の例では、この新しいAPIの最も重要な部分を示します.

1.ロッククロック


Clockクラスは現在の日時にアクセスする方法を提供し、Clockは時間領域に敏感であり、Systemの代わりに使用することができる.CurrentTimeMillis()を使用して、現在のマイクロ秒数を取得します.ある特定の時点をInstantクラスで表すこともでき、Instantクラスは古いjavaを作成するために使用することもできる.util.Dateオブジェクト.
Clock clock = Clock.systemDefaultZone();
long millis = clock.millis();
Instant instant = clock.instant();
Date legacyDate = Date.from(instant);   // legacy java.util.Date

2.Timezonesタイムゾーン


新しいAPIではタイムゾーンはZoneIdで表される.タイムゾーンは、静的メソッドofを用いて容易に取得することができる.タイムゾーンはUTSまでの時間差を定義し、Instantポイントオブジェクトからローカル日付オブジェクトへの変換が極めて重要です.
System.out.println(ZoneId.getAvailableZoneIds());
// prints all available timezone ids
ZoneId zone1 = ZoneId.of("Europe/Berlin");
ZoneId zone2 = ZoneId.of("Brazil/East");
System.out.println(zone1.getRules());
System.out.println(zone2.getRules());
// ZoneRules[currentStandardOffset=+01:00]
// ZoneRules[currentStandardOffset=-03:00]

3.ローカルタイム


LocalTimeは、午後10時、または17:30:15などのタイムゾーン情報のない時間を定義します.次の例では、前のコードで作成したタイムゾーンを使用して2つのローカル時間を作成します.その後、時間を比較し、2つの時間差を時間と分で計算します.
LocalTime now1 = LocalTime.now(zone1);
LocalTime now2 = LocalTime.now(zone2);
System.out.println(now1.isBefore(now2));  // false
long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
System.out.println(hoursBetween);       // -3
System.out.println(minutesBetween);     // -239

LocalTimeは、解析時間文字列を含むオブジェクトの作成を簡略化するための複数のファクトリメソッドを提供します.
LocalTime localTime= LocalTime.of(23, 59, 59);
System.out.println(localTime);       // 23:59:59
DateTimeFormatter germanFormatter =
    DateTimeFormatter
        .ofLocalizedTime(FormatStyle.SHORT)
        .withLocale(Locale.GERMAN);
LocalTime leetTime = localTime.format(germanFormatter);
System.out.println(leetTime);   

4.LocalDateローカル日付


LocalDateは、2014-03-11などの正確な日付を示しています.このオブジェクトの値は可変で、LocalTimeとほぼ一致します.次の例では、Dateオブジェクトに日/月/年を加算する方法を示します.また、これらのオブジェクトは可変であり、操作は常に新しいインスタンスを返します.
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
LocalDate yesterday = tomorrow.minusDays(2);
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek);    // FRIDAY

文字列からLocalDateタイプを解析するのは、LocalTimeを解析するのと同じように簡単です.
DateTimeFormatter germanFormatter =
    DateTimeFormatter
        .ofLocalizedDate(FormatStyle.MEDIUM)
        .withLocale(Locale.GERMAN);
LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter);
System.out.println(xmas);   // 2014-12-24

5.LocalDateTimeローカル日時
LocalDateTimeは時間と日付を同時に表し、前の2つのセクションの内容が1つのオブジェクトに統合されたことに相当します.LocalDateTimeはLocalTimeやLocalDateと同様に可変ではありません.LocalDateTimeは、特定のフィールドにアクセスする方法を提供します.
LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);
 

DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
System.out.println(dayOfWeek);      // WEDNESDAY

Month month = sylvester.getMonth();
System.out.println(month);          // DECEMBER

long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);
System.out.println(minuteOfDay);    // 1439

タイムゾーン情報を付加するだけで、それを1つの時点のInstantオブジェクトに変換することができ、Instantの時点オブジェクトは簡単に古いjavaに変換することができる.util.Date.
Instant instant = sylvester
        .atZone(ZoneId.systemDefault())
        .toInstant();
 

Date legacyDate = Date.from(instant);
System.out.println(legacyDate);     // Wed Dec 31 23:59:59 CET 2014

LocalDateTimeをフォーマットするのは、フォーマット時間と日付が同じで、事前に定義されたフォーマットを使用する以外に、自分でフォーマットを定義することもできます.
DateTimeFormatter formatter =
    DateTimeFormatter
        .ofPattern("MMM dd, yyyy - HH:mm");
 

LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter);
String string = formatter.format(parsed);
System.out.println(string);     // Nov 03, 2014 - 07:13

 
とjava.text.NumberFormatとは異なり、新しいDateTimeFormatterは可変なので、スレッドが安全です.