본문 바로가기
Study/Java

Java에서 날짜 빼기

by 오늘만 사는 여자 2022. 3. 15.
728x90
반응형

이 기사에서는 Java에서 두 날짜를 빼거나 두 날짜 간의 차이를 얻는 방법을 설명합니다.

java.util.Date를 사용하여 Java에서 두 개의 날짜를 뺍니다

java.text.SimpleDateFormat 클래스는 지정된 패턴에 따라 날짜를 형식화하고 구문 분석하는 데 사용됩니다. 두 날짜 간의 시간 차이의 절대 값을 밀리 초 단위로 계산합니다.

TimeUnit 클래스의convert()메서드는 시간 기간과 기간 단위 인 두 개의 매개 변수를받습니다. TimeUnit 객체time을 만들고convert()메서드를 사용하여 밀리 초를 일로 변환합니다.

import java.text.SimpleDateFormat;  
import java.util.Date; 
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
        Date firstDate = sdf.parse("04/22/2020");
        Date secondDate = sdf.parse("04/27/2020");

        long diff = secondDate.getTime() - firstDate.getTime();

        TimeUnit time = TimeUnit.DAYS; 
        long diffrence = time.convert(diff, TimeUnit.MILLISECONDS);
        System.out.println("The difference in days is : "+diffrence);

    }
}

출력:

The difference in days is : 5

java.time.Duration 및java.time.Period를 사용하여 Java에서 두 날짜를 뺍니다

Duration클래스는 시간을 초 및 나노초 단위로 측정하는 반면 Period클래스는 시간을 년, 월, 일 단위로 측정합니다. atStartofDay()메소드는 현지 날짜에 자정 시간을 추가합니다.

두 날짜의 차이로 Period객체를 얻는 반면,between()메서드를 사용하여Duration객체로 두 순간의 차이를 얻습니다. 짧은 시간에는 Duration이 선호됩니다.

기간 diff는 toDays()를 사용하여 일로 변환됩니다. 마찬가지로getYears(),getMonths(),getDays()를 사용하여Period의 날짜 단위를 가져올 수 있습니다.

import java.time.LocalDate;  
import java.time.format.DateTimeFormatter;
import java.time.Duration;
import java.time.Period;

public class Main {
    public static void main(String[] args) throws Exception {
        LocalDate d1 = LocalDate.parse("2020-05-06", DateTimeFormatter.ISO_LOCAL_DATE);
        LocalDate d2 = LocalDate.parse("2020-05-30", DateTimeFormatter.ISO_LOCAL_DATE);

        LocalDate d3 = LocalDate.parse("2018-05-06", DateTimeFormatter.ISO_LOCAL_DATE);
        LocalDate d4 = LocalDate.parse("2020-01-23", DateTimeFormatter.ISO_LOCAL_DATE);

        Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
        Period period = Period.between(d3, d4);

        long diffDays = diff.toDays();
        int years = Math.abs(period.getYears());
        int months = Math.abs(period.getMonths());
        int days = Math.abs(period.getDays());
        System.out.println("Diffrence between dates is : "+diffDays + "days");
        System.out.println("Diffrence is : "+years+" year, "+months+" months, "+days+" days");
    }
}

출력:

Diffrence between dates is : 24days
Diffrence is : 1 year, 8 months, 17 days

Java에서 두 개의 날짜를 빼려면java.time.temporal.ChronoUnit을 사용하세요

Java 8에서 Time API는 TemporalUnit인터페이스를 사용하여 날짜-시간 단위를 나타냅니다. 각 단위는between()이라는 메서드의 구현을 제공합니다. 이 방법은 두 시간 객체 사이의 시간을 계산합니다.

ChronoUnit은 날짜, 시간 또는 날짜-시간을 조작 할 수있는 단위 기반 액세스를 제공하는 표준 날짜-시간 단위 집합입니다.

import java.time.temporal.ChronoUnit;
import java.time.LocalDate;  
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) throws Exception {
        LocalDate dBefore = LocalDate.parse("2018-05-06", DateTimeFormatter.ISO_LOCAL_DATE);
        LocalDate dAfter = LocalDate.parse("2018-05-30", DateTimeFormatter.ISO_LOCAL_DATE);

        long diff = ChronoUnit.DAYS.between(dBefore, dAfter);
        System.out.println("difference is : "+diff);
    }
}

출력:

difference is : 24

Java에서 두 개의 날짜를 빼려면java.time.temporal.Temporal until()을 사용하세요

until()메서드는 지정된 단위로 다른 시간까지의 시간을 계산합니다. 종료가 시작 전이면 결과는 음수입니다.

import java.time.temporal.Temporal;
import java.time.temporal.ChronoUnit;
import java.time.LocalDate;  
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) throws Exception {
        LocalDate dBefore = LocalDate.parse("2018-05-21", DateTimeFormatter.ISO_LOCAL_DATE);
        LocalDate dAfter = LocalDate.parse("2018-05-30", DateTimeFormatter.ISO_LOCAL_DATE);

        long diff = dBefore.until(dAfter,ChronoUnit.DAYS);
        System.out.println("difference is : "+diff +" days");
    }
}

출력:

difference is : 9 days
 
 
728x90
반응형

댓글