文字列を日時(ZonedDateTime)に変換する
package com.example;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Example {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssZ");
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2020-01-01 00:00:00+0900", formatter);
System.out.println(zonedDateTime);
}
}
実行結果:
2020-01-01T00:00+09:00
文字列を日時(LocalDateTime)に変換する
package com.example;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Example {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse("2020-01-01 00:00:00", formatter);
System.out.println(localDateTime);
}
}
実行結果:
2020-01-01T00:00+09:00
日時を文字列に変換・フォーマットする
package com.example;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Example {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssZ");
ZonedDateTime zonedDateTime = ZonedDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault());
System.out.println(formatter.format(zonedDateTime));
System.out.println(zonedDateTime.format(formatter));
}
}
実行結果:
2020-01-01 00:00:00+0900
2020-01-01 00:00:00+0900