본문 바로가기
Java

Java 시간 차이 구하기(날짜 비교)

by Dokon Jang 2021. 2. 18.
반응형

Java 시간 차이 구하기(날짜 비교)

날짜 시간 관련 로직을 구현시 Calendar 클래스를 많이 사용하고 있습니다.
Calendar클래스를 이용한 시간 차이를 구하는 간단한 예제입니다.

[소스]

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class TimeCalculate {

	public static void main(String[] args) {
		
		SimpleDateFormat hhmmssSSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		
		Calendar before = Calendar.getInstance();
		System.out.println("BEFORE : " + hhmmssSSS.format(before.getTime()));
		
		try{Thread.sleep(5000);}catch(Exception e) {}
		
		Calendar after = Calendar.getInstance();
		System.out.println("AFTER : " + hhmmssSSS.format(after.getTime()));
		
		int diffHour = after.get(Calendar.HOUR_OF_DAY) - before.get(Calendar.HOUR_OF_DAY);
		int diffMinute = after.get(Calendar.MINUTE) - before.get(Calendar.MINUTE);
		int diffSecond = after.get(Calendar.SECOND) - before.get(Calendar.SECOND);
		int diffMillisecond = after.get(Calendar.MILLISECOND) - before.get(Calendar.MILLISECOND);
		
		System.out.println("시 : " + diffHour);
		System.out.println("분 : " + diffMinute);
		System.out.println("초 : " + diffSecond);
		System.out.println("밀리세컨드 : " + diffMillisecond);
	}
}



[결과]

 

* SimpleDateFormat 관련 예제는 아래의 포스트를 참고하세요.

https://docko.tistory.com/entry/Java-SimpleDateFormat-%ED%8C%A8%ED%84%B4?category=640361

 

Java SimpleDateFormat 패턴

SimpleDateFormat의 패턴 사용 방법입니다. 1 2 3 4 5 6 7 8 9 10 11 //사용예제 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String format = sdf.format(Calendar.getInstance().getTime(..

docko.tistory.com

 

반응형

댓글