일단기록/간단기록
[JAVA] 시간 계산 하기
겟츄
2022. 5. 20. 14:47
자바에서 시간 관련 클래스는 Date, Calendar, Time이 있는데 Date, Calendar 는 java.util 패키지에 있고 LocalTime ,LocalDate, LocalDateTime 은 java.time 패키지 안에 있다. 그런데 안드로이드에서 time 패키지를 사용하려고 하면 특정 버전 이하의 api 일 때 사용이 불가능하기 때문에 Calendar를 이용해 시간 관련 처리를 하고자 한다.
public static void main(String[] args) {
// 캘린더
Calendar cal = Calendar.getInstance();
// 캘린더에서 년 월 일 가져오기
System.out.println("지금 년도는 : "+cal.get(Calendar.YEAR));
System.out.println("지금 월은 : "+cal.get(Calendar.MONTH));
System.out.println("지금 일은 : "+cal.get(Calendar.DATE));
// 월에 1 더하기
cal.add(Calendar.MONTH, 1);
System.out.println(cal.getTime());
// 월에 1 빼기
cal.add(Calendar.MONTH, -1);
System.out.println(cal.getTime());
System.out.println(new SimpleDateFormat("년월일 yyyy-MM-dd 시간 HH:mm:ss").format(cal.getTime()));
}
시간 계산을 편하게 할 수 있다. 생성된 Calendar의 MONTH에 1을 더한 상태를 출력한 다음 -1 을 한 날짜를 출력 했을때 오늘 시간이 나오는 것을 볼 때 내부 값이 초기화되는 것이 아니라 남아 있는 듯 하다.
또한 월이 0부터 시작하기 때문에 현재 월은 +1 해주어야 현재 월이 나온다.
int currentMonth = current.get(Calendar.MONTH) + 1;