Java

Java_날짜와 시간 클래스

ssmm95 2024. 10. 16. 10:50

Java는 컴퓨터의 날짜 및 시각을 읽을 수 있도록 java.util 패키지에서 Date와 calender클래스를 제공하고 있다 

클래스 설명
Date 날짜 정보를 전달하기 위해 사용
Calender 다양한 시간대별로 날짜와 시간을 얻을 때 사용
LocalDateTime 날짜와 시간을 조작할 때 사용

 

◆ Date 클래스 : 날짜만 다룰 때 사용한다(연,월,일) 날짜를 표현 할 때 월, 일, 연도 기준으로 다룬다 (시간정보x)

date now = new Date(); 

 

◆ Calender 클래스 : 달력을 표현하는 추상 클래스이다

Calender now = Calender.getInstance();

int year = now.get(Calender.YEAR); 년도를 리턴
int month = now.get(Calender.MONTH); 월을 리턴
int day = now.get(Calender.DAY_OF_MONTH); 일을 리턴
int week = now.get(Calender.DAY_OF_WEEK); 요일을 리턴
int amPm = now.get(Calender.AM_PM); 오전/오후를 리턴
int hour = now.get(Calender.HOUR); 시를 리턴
int minute = now.get(Calender.MINUTE); 분을 리턴
int second = now.get(Calender.SECOND); 초를 리턴

 

-알고싶은 시간대의 TimeZone 객체를 얻어 getInstance() 메소드의 매가값으로 넘겨주면 된다

TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles");
Calender now = Calender.getInstance ( timeZone );

 

- 날짜와 시간 조작 

Date와 Calender는 날짜와 시간 정보를 얻기에 충분하지만 날짜와 시간을 조작할 수는 없다 

이때 java.time 패키지의 LocalDateTime 클래스가 제공하는 다음 메소드를 이용해보자

 

1. 날짜 더하기/빼기 Plusxxx(), minusxxx() 

LacalDate, LocalTime, LocalDateTime 클래스에서 날짜나 시간을 더하거나 뺄 수 있다

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();  // 오늘 날짜

        // 날짜 더하기
        LocalDate nextWeek = today.plusWeeks(1);  // 1주일 후
        LocalDate nextMonth = today.plusMonths(1);  // 1달 후
        LocalDate nextYear = today.plusYears(1);  // 1년 후

        // 날짜 빼기
        LocalDate lastWeek = today.minusWeeks(1);  // 1주일 전
        LocalDate lastMonth = today.minusMonths(1);  // 1달 전
        LocalDate lastYear = today.minusYears(1);  // 1년 전

        System.out.println(nextWeek);   // 예: 2024-10-23
        System.out.println(nextMonth);  // 예: 2024-11-16
        System.out.println(nextYear);   // 예: 2025-10-16
        System.out.println(lastWeek);   // 예: 2024-10-09
        System.out.println(lastMonth);  // 예: 2024-09-16
        System.out.println(lastYear);   // 예: 2023-10-16
    }
}

 

 

  • plusDays(int days): 주어진 일 수를 더한다
  • plusWeeks(int weeks): 주어진 주 수를 더한다
  • plusMonths(int months): 주어진 달 수를 더한다
  • plusYears(int years): 주어진 년 수를 더한다
  • minusDays(int days): 주어진 일 수를 뺀다
  • minusWeeks(int weeks): 주어진 주 수를 뺀다
  • minusMonths(int months): 주어진 달 수를 뺀다
  • minusYears(int years): 주어진 년 수를 뺸다

2. 시간 더하기/빼기 - Plusxxx(), minusxxx() 

LocalTime, LocalDateTime에서도 시간 조작이 가능하다

import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        LocalTime now = LocalTime.now();  // 현재 시간

        // 시간 더하기
        LocalTime plusHours = now.plusHours(2);  // 2시간 후
        LocalTime plusMinutes = now.plusMinutes(30);  // 30분 후
        LocalTime plusSeconds = now.plusSeconds(45);  // 45초 후

        // 시간 빼기
        LocalTime minusHours = now.minusHours(1);  // 1시간 전
        LocalTime minusMinutes = now.minusMinutes(15);  // 15분 전
        LocalTime minusSeconds = now.minusSeconds(30);  // 30초 전

        System.out.println(plusHours);
        System.out.println(plusMinutes);
        System.out.println(plusSeconds);
        System.out.println(minusHours);
        System.out.println(minusMinutes);
        System.out.println(minusSeconds);
    }
}

 

 

  • plusHours(int hours): 주어진 시간만큼 더한다
  • plusMinutes(int minutes): 주어진 분만큼 더한다
  • plusSeconds(int seconds): 주어진 초만큼 더한다
  • minusHours(int hours): 주어진 시간만큼 뺸다
  • minusMinutes(int minutes): 주어진 분만큼 뺀다.
  • minusSeconds(int seconds): 주어진 초만큼 뺀다

3. 날짜와 시간 설정하기 - withxxx()메서드

특정 연도, 월, 일, 시, 분 등으로 날짜와 시간을 설정할 수 있는 메서드

import java.time.LocalDate;
import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalTime now = LocalTime.now();

        // 날짜 설정
        LocalDate newYearDate = today.withYear(2025);  // 연도 변경
        LocalDate newMonthDate = today.withMonth(12);  // 월 변경
        LocalDate newDayDate = today.withDayOfMonth(1);  // 일 변경

        // 시간 설정
        LocalTime newHourTime = now.withHour(9);  // 시 변경
        LocalTime newMinuteTime = now.withMinute(45);  // 분 변경
        LocalTime newSecondTime = now.withSecond(0);  // 초 변경

        System.out.println(newYearDate);  // 예: 2025-10-16
        System.out.println(newMonthDate); // 예: 2024-12-16
        System.out.println(newDayDate);   // 예: 2024-10-01
        System.out.println(newHourTime);
        System.out.println(newMinuteTime);
        System.out.println(newSecondTime);
    }
}

 

 

  • withYear(int year): 특정 연도로 설정
  • withMonth(int month): 특정 월로 설정
  • withDayOfMonth(int dayOfMonth): 특정 일로 설정
  • withHour(int hour): 특정 시각으로 설정
  • withMinute(int minute): 특정 분으로 설정
  • withSecond(int second): 특정 초로 설정

4. 날짜와 시간 비교하기 - isBefore(), isAfter(), isEqual()

 

리턴타입 메소드(매개변수) 설명
Boolean isAfter(other) 이후날짜인지?
isBefore(other) 이전날짜인지?
isEqual(other) 동일날짜인지?
long until(other,unit) 주어진 단위(unit) 차이를 리턴
import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate futureDate = LocalDate.of(2025, 1, 1);

        // 날짜 비교
        boolean isBefore = today.isBefore(futureDate);  // 현재 날짜가 미래 날짜보다 전인지 확인
        boolean isAfter = today.isAfter(futureDate);    // 현재 날짜가 미래 날짜보다 후인지 확인
        boolean isEqual = today.isEqual(futureDate);    // 두 날짜가 같은지 확인

        System.out.println("현재 날짜가 미래 날짜 이전인가요? " + isBefore);  // true
        System.out.println("현재 날짜가 미래 날짜 이후인가요? " + isAfter);   // false
        System.out.println("두 날짜가 같은가요? " + isEqual);             // false
    }
}

 

  • isBefore(LocalDate date): 지정한 날짜보다 이전인지 확인
  • isAfter(LocalDate date): 지정한 날짜보다 이후인지 확인
  • isEqual(LocalDate date): 지정한 날짜와 같은지 확인

*지피티와함께했음

 

 

'Java' 카테고리의 다른 글

Java_제네릭(Generics)  (0) 2024.10.16
Java_어노테이션(Annotation)  (0) 2024.10.16
Java_리플렉션  (0) 2024.10.16
Java_java.base 모듈  (1) 2024.10.15
소스 작성 부터 실행까지  (2) 2024.09.04