Menu
Coddy logo textTech

시간대 처리

Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨 — 59개 중 59번째.

Java의 ZonedDateTime은 시간대가 포함된 날짜와 시간을 나타냅니다. 다른 시간대와 작업하거나 시간대 간 변환을 할 때 유용합니다.

특정 시간대에서 시간 생성:

ZonedDateTime tokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));

또한 LocalDateTimeZonedDateTime으로 .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"));

위 코드를 실행한 후, newYorktokyo와 동일한 순간을 포함하지만 뉴욕 시간대입니다:

2024-03-15T10:30-04:00[America/New_York]
// Example output

ZonedDateTime을 포맷하려면 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
challenge icon

챌린지

쉬움

convertTime이라는 이름의 메서드를 생성하세요. 이 메서드는 네 개의 인수를 받습니다:

  1. "yyyy-MM-dd HH:mm" 형식의 String (dateTimeStr)
  2. 소스 시간대 ID인 String (sourceZone)
  3. 대상 시간대 ID인 String (targetZone)
  4. 출력에 시간대 오프셋을 포함할지 여부를 나타내는 boolean (showOffset)

이 메서드는 다음을 수행해야 합니다:

  1. 소스 시간대에서 입력된 날짜시간을 파싱합니다
  2. 이를 대상 시간대로 변환합니다
  3. 두 시간에 대한 형식화된 정보를 반환합니다

반환 메시지는 다음과 같아야 합니다:

  • 날짜시간이 유효하지 않은 경우: "Invalid datetime format"을 반환
  • 시간대가 유효하지 않은 경우: "Invalid time zone"을 반환
  • showOffset이 true인 경우: 출력에 오프셋 포함
  • 형식: "Source: [time1], Target: [time2]"

치트 시트

ZonedDateTime은 시간대가 포함된 날짜와 시간을 나타내며, 다양한 시간대를 다룰 때 유용합니다.

특정 시간대에서 시간을 생성합니다:

ZonedDateTime tokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));

LocalDateTime.atZone()을 사용하여 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));
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리와 흐름의 모든 레슨