본문 바로가기

java(자바)

[java(자바)] 자바에서 HH:mm 형식 시간 차 구하는 방법 _디버깅의 눈물

1.java.util.Date 클래스 사용하기

 

 

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

public class TimeDifference {
    public static void main(String[] args) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");

        String time1 = "10:30";
        String time2 = "12:45";

        Date date1 = format.parse(time1);
        Date date2 = format.parse(time2);

        long difference = date2.getTime() - date1.getTime();

        int hours = (int) (difference / (1000 * 60 * 60));
        int minutes = (int) ((difference / (1000 * 60)) % 60);

        System.out.println(hours + "시간 " + minutes + "분 차이입니다.");
    }
}

 

 

위 코드에서는 SimpleDateFormat 클래스를 사용하여 문자열로부터 Date 객체를 생성합니다. getTime() 메소드를 사용하여 두 Date 객체의 차이를 계산한 다음, 시간과 분으로 분리합니다. 이렇게 구한 시간과 분의 차이를 출력하면 됩니다.

 

또한, 이 코드에서는 시간 차이가 24시간을 초과하지 않는 것을 전제로 하고 있습니다. 시간 차이가 24시간을 초과하는 경우에는 Date 클래스 대신에 java.time 패키지의 LocalDateTime 클래스를 사용하면 더욱 간단하게 구현할 수 있습니다.

 

 

2.java.time.LocalTime 사용하기

 

java.time 패키지의 LocalTime 클래스를 사용하여 시간 차이를 계산할 수 있습니다. 예를 들어, 다음과 같은 코드를 사용하여 현재 시간과 다른 시간 간의 차이를 계산할 수 있습니다.

 

 

import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class TimeDifference {
    public static void main(String[] args) throws Exception {

        LocalTime currentTime = LocalTime.now();
        LocalTime otherTime = LocalTime.of(10, 30); // 예시로 10:30으로 가정
        long hoursBetween = ChronoUnit.HOURS.between(currentTime, otherTime);
        long minutesBetween = ChronoUnit.MINUTES.between(currentTime, otherTime)%60;


        System.out.println(hoursBetween + "시간 " + minutesBetween + "분 차이입니다.");
    }
}

 

 

3. Calendar 사용하기

 

java.util 패키지의 Calendar 클래스를 사용하여 시간 차이를 계산할 수도 있습니다. 예를 들어, 다음과 같은 코드를 사용하여 현재 시간과 다른 시간 간의 차이를 계산할 수 있습니다.

 

 

import java.util.Calendar;
import java.util.Date;

public class TimeDifference {
    public static void main(String[] args) throws Exception {

        Calendar currentTime = Calendar.getInstance();
        Calendar otherTime = Calendar.getInstance();
        otherTime.set(Calendar.HOUR_OF_DAY, 10);
        otherTime.set(Calendar.MINUTE, 30); // 예시로 10:30으로 가정

        long millisecondsBetween = currentTime.getTimeInMillis() - otherTime.getTimeInMillis();
        long hoursBetween = millisecondsBetween / (60 * 1000)/60;
        long minutesBetween = millisecondsBetween / (60 * 1000)%60;

		System.out.println(hoursBetween + "시간 " + minutesBetween + "분 차이입니다.");
    }
}

 

 

위의 2,3 방법 중에서는 java.time 패키지의 LocalTime 클래스를 사용하는 것이 더 권장됩니다. 이는 새로운 자바 8에서 추가된 날짜와 시간 API로 더욱 간편하고 성능이 우수하기 때문입니다.