๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/JAVA

[JAVA] ๋‚ ์งœ ๋น„๊ต ํ•˜๊ธฐ (Date, LocalDateTime, LocalDate)

by ynzu๐Ÿค 2021. 12. 21.
๋ฐ˜์‘ํ˜•

1. java.util.Date์—๋Š” ๋‚ ์งœ๋ฅผ ๋น„๊ตํ•  ์ˆ˜ ์žˆ๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ๋‘๊ฐ€์ง€ ์žˆ๋‹ค.

  • after, before ์‚ฌ์šฉ

- before: ์ธ์ž๋ณด๋‹ค ๊ณผ๊ฑฐ์ผ ๋•Œ true
- after: ์ธ์ž๋ณด๋‹ค ๋ฏธ๋ž˜์ผ ๋•Œ true
- equal: ์ธ์ž์™€ ๊ฐ™์„ ๋•Œ true

public void compareDate(Date date1, Date date2){

        if(date1.after(date2)){
            System.out.println("Date1 > Date2");
        }

        if(date1.before(date2)){
            System.out.println("Date1 < Date2");
        }

        if(date1.equals(date2)){
            System.out.println("Date1 = Date2");
        }
 }

 

  • compareTo ์‚ฌ์šฉ

- compareTo > 0 : ์ธ์ž๋ณด๋‹ค ๋ฏธ๋ž˜์ผ ๋•Œ
- compareTo < 0 : ์ธ์ž๋ณด๋‹ค ๊ณผ๊ฑฐ์ผ ๋•Œ
- compareTo = 0 : ์ธ์ž์™€ ๊ฐ™์„ ๋–„

 public void compareDate2(Date date1, Date date2){

        if (date1.compareTo(date2) > 0) {
            System.out.println("Date1 > Date2");
        }
        
        if(date1.compareTo(date2) < 0){
            System.out.println("Date1 < Date2");
        }

        if(date1.compareTo(date2) == 0){
            System.out.println("Date1 = Date2");
        }
}

 

 

2. java.time.LocalDateTime, LocalDate, LocalTime, ZonedDateTime (java 1.8๋ถ€ํ„ฐ ์‚ฌ์šฉ ๊ฐ€๋Šฅ)

- isBefore : ์ธ์ž๋ณด๋‹ค ๊ณผ๊ฑฐ์ผ ๋•Œ true
- isAfter : ์ธ์ž๋ณด๋‹ค ๋ฏธ๋ž˜์ผ ๋•Œ true
- isEqual : ์ธ์ž์™€ ๊ฐ™์„ ๋•Œ true

public void compareDate3(LocalDateTime date1, LocalDateTime date2) {

        if (date1.isBefore(date2)) {
            System.out.println("Date1 < Date2");
        }

        if (date1.isAfter(date2)) {
            System.out.println("Date1 > Date2");
        }

        if (date1.isEqual(date2)) {
            System.out.println("Date1 = Date2");
        }
}
728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€