코딩 스쿨 Java

언어선택 : HTMLCSSJAVAJAVASCRIPTMYSQLSQL PHP

Java Date

자바 날짜와 시간 처리 (Java Date): 개념 및 사용법

자바에서 날짜와 시간을 처리하는 방법은 여러 가지가 있으며, 자바는 다양한 클래스와 라이브러리를 제공합니다. 이 글에서는 자바의 날짜와 시간 처리를 위한 주요 클래스들에 대해 다루고, 각 클래스의 사용법과 특징을 설명합니다.

1. 자바 날짜와 시간 처리 클래스

자바에서는 날짜와 시간을 처리하기 위해 다음과 같은 클래스를 사용합니다:

  1. .util.Date 클래스: 자바의 기본적인 날짜 및 시간 처리를 위한 클래스.
  2. .util.Calendar 클래스: 날짜 및 시간에 대한 더 많은 기능을 제공하는 유틸리티 클래스.
  3. .text.SimpleDateFormat 클래스: 날짜와 시간을 특정 형식으로 변환하기 위한 클래스.
  4. .time 패키지 (Java 8 이상): LocalDate, LocalTime, LocalDateTime, ZonedDateTime 등을 포함한 최신 날짜 및 시간 API.

2.
.util.Date 클래스 사용

Date 클래스는 자바에서 날짜와 시간을 처리하는 가장 기본적인 클래스입니다. 이 클래스는 시스템 시간을 기준으로 한 날짜와 시간을 밀리초 단위로 저장합니다.

Date 클래스 사용 예제

import java.util.Date;

public class Main {
    public static void main(String[] args) {
        // 현재 날짜와 시간 생성
        Date currentDate = new Date();

        // 현재 날짜와 시간 출력
        System.out.println("Current date and time: " + currentDate);
    }
}

출력 예시:

Current date and time: Thu Oct 10 10:20:30 GMT 2024

주요 메서드

Date 클래스는 날짜와 시간을 처리하기 위한 다양한 메서드를 제공합니다. 그러나 자바 1.1 이후로 Date 클래스의 대부분의 메서드는 사용 자제(deprecated) 되었으며, 날짜 및 시간 처리에 대해 더 나은 기능을 제공하는 Calendar 클래스나

.time API로 대체되었습니다.

메서드 설명
getTime() 1970년 1월 1일 00:00:00 UTC 이후의 밀리초를 반환
toString() 날짜와 시간을 문자열로 변환

3. SimpleDateFormat을 사용한 날짜 형식 지정

SimpleDateFormat 클래스는 날짜와 시간을 특정 형식으로 변환할 때 사용됩니다. 이 클래스는 다양한 패턴을 통해 날짜와 시간을 문자열로 변환하거나, 문자열을 날짜 객체로 변환할 수 있습니다.

SimpleDateFormat 사용 예제

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

public class Main {
    public static void main(String[] args) {
        // 현재 날짜와 시간 생성
        Date currentDate = new Date();

        // 날짜 형식 지정 (예: 2024-10-10)
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = dateFormat.format(currentDate);

        // 결과 출력
        System.out.println("Formatted date: " + formattedDate);
    }
}

출력 예시:

Formatted date: 2024-10-10

날짜 형식 패턴

SimpleDateFormat 클래스는 다양한 패턴을 사용하여 날짜 형식을 지정할 수 있습니다. 다음은 주요 패턴입니다:

패턴 설명 예시
yyyy 연도 (4자리) 2024
MM 월 (2자리) 10
dd 일 (2자리) 10
HH 시 (24시간제, 2자리) 15
mm 분 (2자리) 30
ss 초 (2자리) 45

날짜 문자열을 날짜 객체로 변환

SimpleDateFormat을 사용하면 문자열을 날짜 객체로 변환할 수도 있습니다.

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

public class Main {
    public static void main(String[] args) throws Exception {
        String dateString = "2024-10-10";

        // 날짜 형식 지정
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 문자열을 날짜 객체로 변환
        Date date = dateFormat.parse(dateString);

        System.out.println("Date object: " + date);
    }
}

출력 예시:

Date object: Thu Oct 10 00:00:00 GMT 2024

4. Calendar 클래스 사용

Calendar 클래스Date 클래스보다 더 유연하고 강력한 날짜 및 시간 처리 기능을 제공합니다. Calendar는 시간대, 연도, 월, 일, 시, 분, 초 등 개별 요소에 접근하고 조작할 수 있는 메서드를 제공합니다.

Calendar 클래스 사용 예제

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        // 현재 날짜와 시간 생성
        Calendar calendar = Calendar.getInstance();

        // 연도, 월, 일 정보 가져오기
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;  // 월은 0부터 시작하므로 +1
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        System.out.println("Current date: " + year + "-" + month + "-" + day);

        // 날짜 조작: 10일 추가
        calendar.add(Calendar.DAY_OF_MONTH, 10);
        System.out.println("Date after 10 days: " + calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH));
    }
}

출력 예시:

Current date: 2024-10-10
Date after 10 days: 2024-10-20

주요 메서드

메서드 설명
get(int field) 지정된 필드(연도, 월, 일 등)의 값을 반환
set(int field, int value) 지정된 필드의 값을 설정
add(int field, int amount) 지정된 필드에 값을 더하거나 뺌

5.
.time API 사용 (Java 8 이상)

.time 패키지는 자바 8에서 도입된 최신 날짜 및 시간 처리 API로, 기존의 DateCalendar 클래스보다 더 직관적이고 강력한 기능을 제공합니다. 이 API는 불변 객체(Immutable Objects)로 설계되었으며, 다중 스레드 환경에서도 안전하게 사용할 수 있습니다.

주요 클래스

  • LocalDate: 날짜(연도, 월, 일)를 처리하는 클래스.
  • LocalTime: 시간(시, 분, 초)을 처리하는 클래스.
  • LocalDateTime: 날짜와 시간을 함께 처리하는 클래스.
  • ZonedDateTime: 시간대 정보가 포함된 날짜와 시간을 처리하는 클래스.

LocalDate 사용 예제

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        // 현재 날짜 가져오기
        LocalDate currentDate = LocalDate.now();
        System.out.println("Current date: " + currentDate);

        // 특정 날짜 생성
        LocalDate specificDate = LocalDate.of(2024, 10, 10);
        System.out.println("Specific date: " + specificDate);

        // 날짜 조작: 10일 더하기
        LocalDate newDate = currentDate.plusDays(10);
        System.out.println("Date after 10 days: " + newDate);
    }
}

출력 예시:

Current date: 2024-10-10
Specific date: 2024-10-10
Date after 10 days: 2024-10-20

LocalDateTime 사용 예제

import java.time.LocalDateTime;

public class Main {
    public static void main(String[] args) {
        // 현재 날짜와 시간 가져오기
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("Current date and time: " + currentDateTime);

        // 날짜와 시간 조작
        LocalDateTime newDateTime = currentDateTime.plusHours(5).plusDays(1);
        System.out.println("Date and time after 1 day and 5 hours: " + newDateTime);
    }
}

출력 예시:

Current date and time: 2024-10-10T15:30:45
Date and time after 1 day and 5 hours: 2024-10-11T20:30:45

6. 날짜 형식 지정 (DateTimeFormatter)

.time API에서는 DateTimeFormatter 클래

스를 사용하여 날짜와 시간을 특정 형식으로 변환할 수 있습니다.

DateTimeFormatter 사용 예제

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

public class Main {
    public static void main(String[] args) {
        // 현재 날짜와 시간 가져오기
        LocalDateTime currentDateTime = LocalDateTime.now();

        // 날짜 형식 지정
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 날짜와 시간을 형식에 맞게 문자열로 변환
        String formattedDateTime = currentDateTime.format(formatter);
        System.out.println("Formatted date and time: " + formattedDateTime);
    }
}

출력 예시:

Formatted date and time: 2024-10-10 15:30:45

요약

자바에서 날짜와 시간을 처리하는 방법에는 여러 가지가 있으며, 사용 용도에 따라 적절한 클래스를 선택할 수 있습니다:

  • Date 클래스: 기본적인 날짜와 시간 처리.
  • SimpleDateFormat: 날짜 형식 지정과 문자열 변환.
  • Calendar 클래스: 날짜와 시간의 조작이 필요한 경우.
  • .time API (Java 8 이상): 더 강력하고 직관적인 날짜 및 시간 처리 기능을 제공하는 최신 API.

.time API는 특히 불변 객체로 설계되어 더 안전하게 사용할 수 있으며, 더 나은 성능과 유연성을 제공합니다.


copyright ⓒ 스타트코딩 all rights reserved.
이메일 : startcodingim@gamil.com