본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

JAVA

Period와 Duration 날짜/시간의 차이 사칙연산, 유용한 메서드

Period 와 Duration

Period는 날짜의 차이를, Duration은 시간의 차이를 계산한다.

 

 

 

between()

두 날짜의 차이를 나타내는 Period는 between()으로 얻을 수 있다.

LocalDate startDate = LocalDate.of(2023, 10, 15);
LocalDate endDate = LocalDate.of(2024, 3, 20);

Period period = Period.between(startDate, endDate);

System.out.println("Period between start and end date: " + period);
//Period between start and end date: P5M5D

 

 

 

get()

Period 와 Duration에서 특정 필드 값을 얻을 때 사용한다.

LocalTime startTime = LocalTime.of(10, 30, 15);
LocalTime endTime = LocalTime.of(14, 45, 30);

Duration duration = Duration.between(startTime, endTime);

long hours = duration.toHours();
long minutes = duration.minusHours(hours).toMinutes();
long seconds = duration.minusHours(hours).minusMinutes(minutes).getSeconds();

System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
System.out.println("Seconds: " + seconds);
//Hours: 4
//Minutes: 15
//Seconds: 15

 

 

 

Duration을 LocalTime으로 변환하여 get메서드를 사용하기

Period 와 달리 Duration는 시간을 나타내는데 사용되는 클래스지만 getHours(), getMinites메서드를 제공하지않는다.

Duration이 시간을 시간과 분으로만 표현하는것이 아닌 시간, 분, 초, 나노초 등을 포함하는 기간을 나타내기때문이다.

 

 

until()

until()은 between()과 거의 같다. between은 static메서드이고, until은 instance 메서드라는 차이가 있다.

between()메서드는 두개의 LocalDate객체를 인자로 받아 차이를 계산하나 until()은 현 객체부터 다른 객체까지의 차이를 계산 할 수 있어 D-day와 같은 계산에 유리하다.

LocalDate start = LocalDate.of(2024, 1, 1);
LocalDate end = LocalDate.of(2024, 12, 31);
Period period = Period.between(start, end);
LocalDate start = LocalDate.of(2024, 1, 1);
LocalDate end = LocalDate.of(2024, 12, 31);
Period period = start.until(end);

 

 

 

of() with()

Period에는 of(), ofYears(), ofMonths(), ofWeeks(), ofDays()가 있다.

import java.time.Period;

public class Main {
    public static void main(String[] args) {
        // of()
        Period period1 = Period.of(1, 2, 3);
        System.out.println("Period of(1, 2, 3): " + period1);
        //Period of(1, 2, 3): P1Y2M3D

        // ofYears()
        Period period2 = Period.ofYears(2);
        System.out.println("Period ofYears(2): " + period2);
        //Period ofYears(2): P2Y

        // ofMonths()
        Period period3 = Period.ofMonths(3);
        System.out.println("Period ofMonths(3): " + period3);
        //Period ofMonths(3): P3M

        // ofWeeks()
        Period period4 = Period.ofWeeks(4);
        System.out.println("Period ofWeeks(4): " + period4);
        //Period ofWeeks(4): P28D

        // ofDays()
        Period period5 = Period.ofDays(5);
        System.out.println("Period ofDays(5): " + period5);
        //Period ofDays(5): P5D
    }
}

 

 

 

Duration에는 of(), ofDays(), ofHours(), ofMinutes(), ofSeconds()가 있다.

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        // of()
        Duration duration1 = Duration.of(1, 2);
        System.out.println("Duration of(1, 2): " + duration1);
        //Duration of(1, 2): PT1H2S

        // ofDays()
        Duration duration2 = Duration.ofDays(2);
        System.out.println("Duration ofDays(2): " + duration2);
        //Duration ofDays(2): PT48H

        // ofHours()
        Duration duration3 = Duration.ofHours(3);
        System.out.println("Duration ofHours(3): " + duration3);
        //Duration ofHours(3): PT3H

        // ofMinutes()
        Duration duration4 = Duration.ofMinutes(4);
        System.out.println("Duration ofMinutes(4): " + duration4);
        //Duration ofMinutes(4): PT4M

        // ofSeconds()
        Duration duration5 = Duration.ofSeconds(5);
        System.out.println("Duration ofSeconds(5): " + duration5);
        //Duration ofSeconds(5): PT5S
    }
}

 

 

 

특정필드값을 변경하는 with()가 있다.

import java.time.Period;

public class Main {
    public static void main(String[] args) {
        Period period = Period.of(1, 2, 3);
        System.out.println("Original Period: " + period);
        //Original Period: P1Y2M3D

        // 변경된 연도(1 -> 5)
        Period updatedPeriod = period.withYears(5);
        System.out.println("Updated Period withYears(5): " + updatedPeriod);
        //Updated Period withYears(5): P5Y2M3D

        // 변경된 월(2 -> 6)
        updatedPeriod = period.withMonths(6);
        System.out.println("Updated Period withMonths(6): " + updatedPeriod);
        //Updated Period withMonths(6): P1Y6M3D

        // 변경된 일(3 -> 10)
        updatedPeriod = period.withDays(10);
        System.out.println("Updated Period withDays(10): " + updatedPeriod);
        //Updated Period withDays(10): P1Y2M10D
    }
}
import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        Duration duration = Duration.ofHours(3).plusMinutes(30);
        System.out.println("Original Duration: " + duration);
        //Original Duration: PT3H30M

        // 변경된 시간(3 -> 5)
        Duration updatedDuration = duration.withHours(5);
        System.out.println("Updated Duration withHours(5): " + updatedDuration);
        //Updated Duration withHours(5): PT5H30M

        // 변경된 분(30 -> 45)
        updatedDuration = duration.withMinutes(45);
        System.out.println("Updated Duration withMinutes(45): " + updatedDuration);
        //Updated Duration withMinutes(45): PT3H45M

        // 변경된 초(0 -> 15)
        updatedDuration = duration.withSeconds(15);
        System.out.println("Updated Duration withSeconds(15): " + updatedDuration);
        //Updated Duration withSeconds(15): PT3H30M15S
    }
}

 

 

 

multipliedBy, dividedBy

plus(), minus() 외 곱셈과 나눗셈을 위한 메서드가 있다.

Period에는 날짜의 기간을 표현하기 위한것임으로 이에 메서드가 유용하지않아 없다.

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        Duration duration = Duration.ofHours(2);

        // 2를 곱한 Duration
        Duration multipliedDuration = duration.multipliedBy(3);
        System.out.println("Multiplied Duration: " + multipliedDuration);
        //Multiplied Duration: PT6H

        // 음수를 곱한 Duration
        Duration negativeMultipliedDuration = duration.multipliedBy(-2);
        System.out.println("Negative Multiplied Duration: " + negativeMultipliedDuration);
        //Negative Multiplied Duration: PT-4H
    }
}
import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        Duration duration = Duration.ofHours(6);

        // 2로 나눈 Duration
        Duration dividedDuration = duration.dividedBy(2);
        System.out.println("Divided Duration: " + dividedDuration);
        //Divided Duration: PT3H

        // 음수로 나눈 Duration
        Duration negativeDividedDuration = duration.dividedBy(-3);
        System.out.println("Negative Divided Duration: " + negativeDividedDuration);
        //Negative Divided Duration: PT-2H
    }
}

https://standout.tistory.com/1248

 

LocalDate와 LocalTime: get() getLong()특정필드값 가져오기, with() plus() minus() 변경하기, truncatedTo() 0으로

LocalDate와 LocalTime은 java.time 패키지의 가장 기본이 된다. 나머지 클래스들은 이들의 확장. https://standout.tistory.com/1245 java.time패키지: 객체생성 now() of() parse()와 인터페이스, 간격을 나타내는 Period Du

standout.tistory.com

 

 

 

 

isNegative()

계산결과가 음수인지 확인하는 메서드

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        Duration duration1 = Duration.ofHours(2);
        Duration duration2 = Duration.ofHours(-2);
        Duration duration3 = Duration.ZERO;

        System.out.println("Duration1 is negative: " + duration1.isNegative()); // false
        System.out.println("Duration2 is negative: " + duration2.isNegative()); // true
        System.out.println("Duration3 is negative: " + duration3.isNegative()); // false
    }
}

 

isZero()

계산결과가 0인지 확인하는 메서드

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        Duration duration1 = Duration.ofHours(2);
        Duration duration2 = Duration.ofHours(-2);
        Duration duration3 = Duration.ZERO;

        System.out.println("Duration1 is zero: " + duration1.isZero()); // false
        System.out.println("Duration2 is zero: " + duration2.isZero()); // false
        System.out.println("Duration3 is zero: " + duration3.isZero()); // true
    }
}

 

negate()

부호를 반대로 변경하는 메서드

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        Duration duration1 = Duration.ofHours(2);

        Duration negatedDuration = duration1.negated();
        System.out.println("Negated duration of duration1: " + negatedDuration); // PT-2H
    }
}

 

abs()

부호를 없애는 메서드

Duration duration1 = Duration.ofHours(2);
Duration duration2 = Duration.ofHours(-2);

Duration absoluteDuration1 = duration1.abs();
Duration absoluteDuration2 = duration2.abs();
System.out.println("Absolute duration of duration1: " + absoluteDuration1); // PT2H
System.out.println("Absolute duration of duration2: " + absoluteDuration2); // PT2H

 

 

normalized()

월의 값이 12를 넘치지않도록 년으로 바꿔주는 메서드

import java.time.Period;

public class Main {
    public static void main(String[] args) {
        Period period = Period.ofYears(2).plusMonths(15);

        System.out.println("Original period: " + period); //Original period: P2Y15M

        Period normalizedPeriod = period.normalized();
        System.out.println("Normalized period: " + normalizedPeriod);//Normalized period: P3Y3M
    }
}

 

 

Period - toTotalMonths() 년월일을 일 단위는 무시하여 월단위로 변환해서 반환

import java.time.Period;

public class Main {
    public static void main(String[] args) {
        Period period = Period.ofYears(2).plusMonths(6);

        long totalMonths = period.toTotalMonths();
        System.out.println("Total months in period: " + totalMonths);
        //Total months in period: 30
    }
}

 

 

Duration - long toDays(), toHours(), toMinutes(), to Millis() toNanos() 일, 시간, 분, 천분의 일, 나노 초의 단위로 변환해서 반환

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        Duration duration = Duration.ofHours(25).plusMinutes(30);

        long days = duration.toDays();
        long hours = duration.toHours();
        long minutes = duration.toMinutes();
        long millis = duration.toMillis();
        long nanos = duration.toNanos();

        System.out.println("Days: " + days); //Days: 1
        System.out.println("Hours: " + hours); //Hours: 25
        System.out.println("Minutes: " + minutes);//Minutes: 1500
        System.out.println("Milliseconds: " + millis);//Milliseconds: 90000000
        System.out.println("Nanoseconds: " + nanos);//Nanoseconds: 90000000000000
    }
}