タイムゾーンの処理
CoddyのJavaジャーニー「ロジックとフロー」セクションの一部 — レッスン 59/59。
Java の ZonedDateTime は、タイムゾーン付きの日付と時間を表します。異なるタイムゾーンを扱ったり、それら間で変換したりする際に便利です。
特定のタイムゾーンで時刻を作成:
ZonedDateTime tokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));また、LocalDateTime を ZonedDateTime に変換するには .atZone() を使用できます:
LocalDateTime local = LocalDateTime.of(2024, 3, 15, 10, 30);
ZonedDateTime tokyo = local.atZone(ZoneId.of("Asia/Tokyo"));.atZone() は、既存のローカル日時にタイムゾーンを付与し、ZonedDateTime を生成します。
タイムゾーン間で時間を変換:
ZonedDateTime newYork = tokyo.withZoneSameInstant(ZoneId.of("America/New_York"));上記のコードを実行した後、newYork は tokyo と同じ瞬間を含みますが、ニューヨークのタイムゾーンになっています:
2024-03-15T10:30-04:00[America/New_York]
// Example outputZonedDateTime をフォーマットするには、DateTimeFormatter を使用します。パターン文字 Z または xxx は UTC オフセット(例: +09:00)をフォーマットし、VV はゾーン ID(例: Asia/Tokyo)をフォーマットします:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm xxx");
String formatted = tokyo.format(formatter);
// Example: 2024-03-15 10:30 +09:00チャレンジ
簡単convertTime という名前のメソッドを作成し、4つの引数を受け取るようにしてください:
- 形式 "yyyy-MM-dd HH:mm" の String(
dateTimeStr) - ソースタイムゾーン ID の String(
sourceZone) - ターゲットタイムゾーン ID の String(
targetZone) - 出力にタイムゾーンオフセットを含めるかどうかの boolean(
showOffset)
このメソッドは以下を行うべきです:
- ソースタイムゾーンで入力された日時を解析する
- それをターゲットタイムゾーンに変換する
- 両方の時間のフォーマットされた情報を返す
戻り値のメッセージは以下の通りです:
- 日時が無効な場合: "Invalid datetime format" を返す
- ゾーンが無効な場合: "Invalid time zone" を返す
- showOffset が true の場合:出力にオフセットを含める
- 形式: "Source: [time1], Target: [time2]"
チートシート
ZonedDateTime は、タイムゾーン付きの日付と時間を表し、異なるタイムゾーンを扱うのに便利です。
特定のゾーンで時刻を作成:
ZonedDateTime tokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));.atZone() を使用して LocalDateTime を ZonedDateTime に変換:
LocalDateTime local = LocalDateTime.now();
ZonedDateTime zoned = local.atZone(ZoneId.of("Asia/Tokyo"));ゾーン間で時刻を変換:
ZonedDateTime newYork = tokyo.withZoneSameInstant(ZoneId.of("America/New_York"));Z または xxx パターンを使用して、UTC オフセットを含む ZonedDateTime をフォーマット:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm xxx");
String formatted = zoned.format(formatter);
// Example: 2024-03-15 10:30 +09:00自分で試してみよう
import java.util.Scanner;
import java.time.*;
import java.time.format.*;
public class Main {
public static String convertTime(String dateTimeStr, String sourceZone,
String targetZone, boolean showOffset) {
// ここにコードを記述してください
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String dateTimeStr = scanner.nextLine();
String sourceZone = scanner.nextLine();
String targetZone = scanner.nextLine();
boolean showOffset = Boolean.parseBoolean(scanner.nextLine());
System.out.println(convertTime(dateTimeStr, sourceZone, targetZone, showOffset));
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。