0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ISO時刻基準変換例

Last updated at Posted at 2024-02-06

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.List;

public class DateTimeConversionTest {

public static void main(String[] args) {
    List<String> sampleIsoDateTimes = getIsoDateTimeSamples();

    for (String inputIsoDateTime : sampleIsoDateTimes) {
        try {
            String formattedDateTime = convertToCustomFormat(inputIsoDateTime);
            System.out.println(inputIsoDateTime + " => " + formattedDateTime + " 変換されました");
        } catch (DateTimeParseException e) {
            System.out.println(inputIsoDateTime + " このサンプルは変換されませんでした");
        }
    }
}

private static List<String> getIsoDateTimeSamples() {
    return Arrays.asList(
        "2021-11-11",
        "2021-11-11T13:23",
        "2021-11-11T13:23:45",
        "2021-11-11T13:23:45.123",
        "2021-11-11T13:23:45Z",
        "2021-11-11T13:23:45+09:00",
        "2021-11-11T13:23:45-09:00",
        "2021-11-11T13:23:45.123+09:00",
        "2021-11-11T13:23:45.123-09:00"
    );
}

private static String convertToCustomFormat(String inputIsoDateTime) {
    try {
        ZonedDateTime dateTime;
        try {
            dateTime = ZonedDateTime.parse(inputIsoDateTime, DateTimeFormatter.ISO_DATE_TIME);
        } catch (DateTimeParseException e) {
            // タイムゾーン情報がない場合はLocalDateTimeにパースしてからZonedDateTimeに変換
            LocalDateTime localDateTime = LocalDateTime.parse(inputIsoDateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            dateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Asia/Tokyo"));
        }
        // カスタムフォーマットを使用して出力
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss,SSSSSSXXX");
        return dateTime.format(customFormatter);
    } catch (DateTimeParseException e) {
        // 解析に失敗した場合
        throw new DateTimeParseException("Failed to parse date time: " + inputIsoDateTime, inputIsoDateTime, 0);
    }
}

}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?