[JAVA] 12-8. 날짜 클래스의 특징 및 메서드 종류

Re_Go·2024년 7월 5일
0

JAVA

목록 보기
37/37
post-thumbnail

1. Calendar

Calendar 클래스는 뒤에 소개할 Date 클래스와 마찬가지로 시스템의 시간이나 사용자가 정의하는 시간을 표현할 수 있게 해주는 클래스입니다. 특히 Calendar는 날짜와 시간의 특정 부분을 클래스가 제공하는 메서드로 임의 변경 하는 것도 가능하고, 클래스에서 제공하는 상수로 제공 받아 사용할 수도 있습니다.

그러나 Calendar 클래스가 추상 클래스인 특성상 인스턴스를 new 키워드로 생성하는 방법이 허용되지 않고, 다만 getInstance 메서드로 하나의 인스턴스만 생성 하면서 활용하는 방법으로 사용할 수 있습니다.

이러한 Calendar 클래스의 생성자 매개변수로는 ("시간대", "지역")을 전달하게 되는데, 이 둘을 지정하지 않을 경우 시스템의 현재 요일 및 시간과 지역을 기준으로 지정됩니다. 물론 이 부분을 사용자가 직접 전달하는 것 또한 가능하고요.

// 기본 사용법
Calendar cal = Calendar.getInstance();

// 시간대를 지정하는 경우 : TimeZone 클래스의 메서드를 사용해 원하는 지역의 시간대를 생성하고 매개변수로 전달합니다.
//TimeZone tz = TimeZone.getTimeZone("America/New_York");
Calendar cal = Calendar.getInstance(tz);

// 시간대와 지역을 지정하는 경우 : TimeZone 클래스로 지역의 시간대를 설정하고, Locale 클래스의 나라별 상수값을 매개변수로 전달하는 것 또한 가능합니다.
TimeZone tz = TimeZone.getTimeZone("America/New_York");
Locale locale = Locale.US;
Calendar cal = Calendar.getInstance(tz, locale);

특히 이러한 Calendar 메서드의 제일 큰 장점이라고 한다면 앞서 언급한대로 get 메서드를 사용해 Calendar 클래스의 특정 시간대를 나타내는 상수값을 추출하는 것이 가능하다는 건데요.

이때 두번째 매개변수로 사용자가 임의 지정할 값으로서 전달은 가능하나, 애초에 가져오는 값 자체를 정확하게 가져오려는 목적상 부합하지 않는 행위이기 때문에, 두번째 매개변수는 지정하지 않는 편이 좋다고 생각하시면 되겠습니다.

// 년, 월, 일
System.out.println("년 : " + cal.get(Calendar.YEAR));
System.out.println("월 : " + (cal.get(Calendar.MONTH)+1));
System.out.println("일 : " + cal.get(Calendar.DATE));

// 요일 번호 : 일(1), 월(2) ~ 토(7)까지 존재
System.out.println("요일 번호 : " + cal.get(Calendar.DAY_OF_WEEK));

// 시, 분, 초
// 오전 : 0, 오후 : 1
System.out.println("오전/오후 : " + cal.get(Calendar.AM_PM));
// 12시각제(0~11)
System.out.println("시간 : " + cal.get(Calendar.HOUR));
// 24시각제(0~23)
System.out.println("시간 : " + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("분 : " + cal.get(Calendar.MINUTE));
System.out.println("초 : " + cal.get(Calendar.SECOND));
// 1000분의 1초
System.out.println("밀리초 : " + cal.get(Calendar.MILLISECOND));
// 전체 시간을 전부 밀리초로 환산해 얻어오는 메서드. 정확한 일자를 획득하기 위해서는 1000으로 나누어 밀리초로 환산한 후 각각 60(초) * 60(분) * 24(시간) 중 얻고자 하는 시간 형식에 따라 곱하면 해당하는 특정 시간대를 획득할 수 있습니다. 
System.out.println((cal.getTimeInMillis() / 1000) * 60) -> 현재 밀리초를 분 단위로 획득
System.out.println((cal.getTimeInMillis() / 1000) * 60 * 60) -> 현재 밀리초를 시간 단위로 획득
System.out.println((cal.getTimeInMillis() / 1000) * 60 * 60 * 24) -> 현재 밀리초를 일수 단위로 획득
// 단 월 단위는 30으로 나누어 떨어지지 않는 달들이 존재하기에 권장 x

2. Date

Calendar와 비슷한 기능을 하는 클래스로, 인스턴스를 생성한 뒤 정해진 포맷 형식에 맞춰 날짜와 시간이 출력 되는 자바의 기본 날짜&시간 클래스 인데요. 다만 Date 클래스의 인스턴스를 이용해 사용자가 직접 포맷 형식을 바꾸어 출력하기 위해서는 인스턴스의 get메서드로 특정 시간대를 일일이 불러와 String 클래스의 format 메서드로 변환을 해줘야 하기 때문에

Date 클래스 자체에서의 포맷팅 변화 방식 보다는 SimpleDateFormat 클래스를 이용해 원하는 포맷 방식으로 인스턴스를 생성한 뒤 해당 인스턴스의 format 메서드로 Date 클래스의 인스턴스를 포맷 하는 방식이 주를 이루고 있다고 합니다.

그냥 Date와 SimpleDateFormat은 짝궁이라고 생각하시면 편합니다.

Date 클래스와 String 클래스의 format 메서드를 사용하는 경우

import java.util.Date;

public class DateFormattingExample {
    public static void main(String[] args) {
        Date now = new Date();
public class DateFormattingExample {
    public static void main(String[] args) {
        Date now = new Date();

        // Date 객체에서 연, 월, 일, 시간, 분, 초 추출
        int year = now.getYear() + 1900; // 연도는 1900을 더해야 정확한 값이 나옴
        int month = now.getMonth() + 1; // 월은 0부터 시작하므로 +1 해야 함
        int day = now.getDate();
        int hours = now.getHours();
        int minutes = now.getMinutes();
        int seconds = now.getSeconds();

        // 원하는 형식으로 포맷팅
        String formattedDate = String.format("%04d-%02d-%02d %02d-%02d-%02d", year, month, day, hours, minutes, seconds);
        System.out.println("포맷된 날짜: " + formattedDate);
    }
}year = now.getYear() + 1900; // 연도는 1900을 더해야 정확한 값이 나옴
        int month = now.getMonth() + 1; // 월은 0부터 시작하므로 +1 해야 함
        int day = now.getDate();
        int hours = now.getHours();
        int minutes = now.getMinutes();
        int seconds = now.getSeconds();

        // 원하는 형식으로 포맷팅
        String formattedDate = String.format("%04d-%02d-%02d %02d-%02d-%02d", year, month, day, hours, minutes, seconds);
        System.out.println("포맷된 날짜: " + formattedDate);
    }
}

Date 클래스와 SimpleDateFormat의 format 메서드를 사용하는 경우

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

public class Ex08_Date_SimpleDateFormat {
	public static void main(String[] args) {
		
		Date now = new Date();
		System.out.println(now);
		
		// SimpleDateFormat
		// 년 : yy, yyyy
		// 월 : M, MM (다른 변수들과 다르게 분도 알파벳 m으로 되어있기에 월만 대문자 M)
		// 일 : d, dd
		// 요일 : E
		// 오전오후 : a
		// 시 : hh(12시각제), HH(24시각제)
		// 분 : mm
		// 초 : ss
		
		//SimpleDateFormat 인스턴스를 생성할 때 사용자가 지정된 구분자를 기준으로 원하는 포맷 형식으로 지정 가능 
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		SimpleDateFormat format2 = new SimpleDateFormat("yy/MM/dd");
		SimpleDateFormat format3 = new SimpleDateFormat("yyyy년 MM월 dd일 E요일");
		SimpleDateFormat format4 = 
				new SimpleDateFormat("M월 W번 째 주 d번째 날, F번 째 E요일");
	
		System.out.println(format1.format(now));
		System.out.println(format2.format(now));
		System.out.println(format3.format(now));
		System.out.println(format4.format(now));
	}
}

3. Time

자바 8버전부터 Date와 SimpleDateFormat의 단점을 보완하기 위해 제공된 API라고 하며, 클래스로는 LocalDate(날짜), LocalTime(시간), LocalDateTime(날짜와 시간)가 있으며, SimpleDateFormat의 format 메서드 대신 DateTimeFormatter 클래스의 format을 사용하여 직관적인 메서드들의 안전성과 정확성을 더욱 극대화 시켰다고 합니다.

특히 Date와 Calendar의 고질적인 문제중 하나였던 month + 1 (month가 1이 아니라 0부터 시작)하는 문제를 해결하여 월의 정보를 갖고올 때 이젠 1을 붙이지 않아도 된다고 합니다.

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

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

        // ofPattern 메서드로 날짜와 시간 포맷 형식을 지정
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 현재 날짜와 시간 정보(LocalDateTime.noe()의 반환값)을 전달 받은 포맷 패턴으로 변환 후 출력
        String formattedDateTime = currentDateTime.format(formatter);
        System.out.println("현재 날짜와 시간: " + formattedDateTime);

        // 날짜 연산 예시 (현재 날짜에서 하루를 더함)
        LocalDate tomorrow = currentDate.plusDays(1);
        System.out.println("내일 날짜: " + tomorrow);

        // 시간 간격 계산 예시 (현재 날짜와 시간에서 3시 30분 가량을 늘린 후 출력)
        LocalDateTime futureDateTime = currentDateTime.plusHours(3).plusMinutes(30);
        System.out.println("현재 시간으로부터 3시간 30분 후: " + futureDateTime);
    }
}
profile
인생은 본인의 삶을 곱씹어보는 R과 타인의 삶을 배워 나아가는 L의 연속이다.

0개의 댓글