[JAVA] 날짜 비교

SimpleDateFormat을 이용한 날짜 비교하는 방법에 대해 알아보겠습니다.

소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {

public static long getDayCount( String start, String end ) {
SimpleDateFormat format = new SimpleDateFormat( "yyyy-M-d" );

long diff = -1;

try {
Date dateStart = format.parse( start );
Date dateEnd = format.parse( end );

// time is always 00:00:00 so rounding should help to ignore the
// missing hour when going from winter to summer time as well as the
// extra hour in the other direction
diff = Math.round( ( dateEnd.getTime() - dateStart.getTime() ) / (double)( 60 * 60 * 24 * 1000 ) );
}
catch ( Exception e ) {
e.printStackTrace();
}

return diff;
}

public static void main( String[] args ) {
long diff = getDayCount( "2021-1-1", "2021-4-26" );
System.out.println( "결과 : " + diff + " 일" );
}
}

결과

1
결과 : 115
Share