[java] 자바에서 날짜와 시간 파싱하기

자바에서는 날짜와 시간을 파싱하고 조작하는 데 사용할 수 있는 많은 기능과 클래스가 있습니다. 이 글에서는 자바에서 날짜와 시간을 파싱하는 방법을 알아보겠습니다.

1. SimpleDateFormat을 사용한 날짜 파싱

SimpleDateFormat 클래스는 입력된 패턴에 맞는 문자열을 파싱하여 Date 객체로 변환할 수 있습니다. 예를 들어, “yyyy-MM-dd” 형식의 문자열로부터 Date 객체를 생성하려면 다음과 같이 작성할 수 있습니다.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateParsingExample {
    public static void main(String[] args) {
        String dateString = "2022-01-01";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date date = dateFormat.parse(dateString);
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

위의 예제에서는 SimpleDateFormat 객체를 생성하고, parse() 메서드를 사용하여 문자열을 Date 객체로 변환합니다. 만약 입력된 문자열이 지정된 패턴과 일치하지 않는 경우 ParseException이 발생할 수 있으므로 에러 처리를 해주어야 합니다.

2. LocalDateTime을 사용한 날짜와 시간 파싱

Java 8부터는 java.time 패키지에 날짜와 시간을 다루기 위한 새로운 API가 도입되었습니다. LocalDateTime 클래스는 날짜와 시간의 정보를 저장하고 조작하는 데 사용됩니다. 문자열을 LocalDateTime 객체로 파싱하기 위해서는 DateTimeFormatter를 사용하면 됩니다.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeParsingExample {
    public static void main(String[] args) {
        String dateTimeString = "2022-01-01T12:34:56";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

        LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
        System.out.println(dateTime);
    }
}

위의 예제에서는 DateTimeFormatter를 사용하여 지정된 패턴에 맞는 문자열을 파싱하여 LocalDateTime 객체로 변환합니다. ofPattern() 메서드를 사용하여 날짜와 시간의 형식을 지정할 수 있습니다.

결론

자바에서는 SimpleDateFormatDateTimeFormatter를 사용하여 날짜와 시간을 문자열에서 파싱하여 객체로 변환할 수 있습니다. 패턴에 맞지 않는 문자열이 주어진 경우 예외를 처리해야 하며, 정확한 패턴을 지정하여 변환할 데이터의 형식을 명시적으로 지정해야 합니다.

참고 자료