https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html
Calendar (Java Platform SE 8 )
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields. For example, to roll the current date up by one day, you can achieve it by calling: roll(Calendar.DATE, true). When rolling on the year or Calendar.YE
docs.oracle.com
공식문서를 보고 필요한 부분을 번역해서 정리 했습니다.
1. 특정 날짜의 시간을 변환하는 추상 클래스다.
The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week. An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).
Calendar 클래스는 특정 순간의 시간을 변환하며, YEAR, MONTH, DAY_OF_MONTH, HOUR 등의 calendar 필드 집합 간에 다음 주 날짜 가져오기와 같은 calendar 필드를 조작하는 방법을 제공하는 추상 클래스입니다. 특정 시간은 Epoch, 1970년 1월 1일 00:00:00.000 GMT(그레고리안)의 오프셋인 밀리초 값으로 나타낼 수 있습니다.
2. getInstance 메소드
: 현재 날짜 및 시간으로 초기화된 Calendar 개체 반환
: 추상 클래스이므로 getInstance()를 통해 구현된 객체를 얻어야 한다.
Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time:
다른 로케일 구분 클래스와 마찬가지로, Calendar 는 이러한 유형의 일반적으로 유용한 객체를 가져오기 위한 클래스 메서드 getInstance를 제공합니다. Calendar의 getInstance 메서드는 캘린더 필드가 현재 날짜 및 시간으로 초기화된 Calendar 객체를 반환합니다:
3. set 메소드 : 필드 값 설정
The calendar field values can be set by calling the set methods. Any field values set in a Calendar will not be interpreted until it needs to calculate its time value (milliseconds from the Epoch) or values of the calendar fields. Calling the get, getTimeInMillis, getTime, add and roll involves such calculation.
Calendar 필드 값은 set 메소드를 호출하여 설정할 수 있습니다. Calendar에 설정된 필드 값은 시간 값(Epoch에서 밀리초 단위) 또는 Calendar 필드의 값을 계산해야 합니다. get, getTimeInMillis, getTime, add and roll을 호출하려면 이러한 계산이 필요합니다.
set(f, value) changes calendar field f to value. In addition, it sets an internal member variable to indicate that calendar field f has been changed. Although calendar field f is changed immediately, the calendar's time value in milliseconds is not recomputed until the next call to get(), getTime(), getTimeInMillis(), add(), or roll() is made. Thus, multiple calls to set() do not trigger multiple, unnecessary computations. As a result of changing a calendar field using set(), other calendar fields may also change, depending on the calendar field, the calendar field value, and the calendar system. In addition, get(f) will not necessarily return value set by the call to the set method after the calendar fields have been recomputed. The specifics are determined by the concrete calendar class.
set(f, value)는 calendar 필드 f를 값으로 변경합니다. 또한 calendar 필드 f가 변경되었음을 나타내는 내부 멤버 변수를 설정합니다. calendar 필드 f가 즉시 변경 되더라도 get(), getTime(), getTimeInMillis(), add() 또는 roll()을 다음에 호출할 때까지 캘린더의 시간 값(밀리초)은 다시 계산되지 않습니다. 따라서 set()를 여러 번 호출해도 불필요한 여러 계산이 트리거되지 않습니다. set()를 사용하여 calendar 필드를 변경하면 calendar 필드, calendar 필드 값 및 calendar 시스템에 따라 다른 calendar 필드도 변경될 수 있습니다. 또한 get(f)는 calendar 필드를 다시 계산한 후 호출에 의해 설정된 값을 set 메서드로 반환하지 않습니다. 구체적인 내용은 구체적인 calendar class 에 의해 결정됩니다.
(필자첨언) set 메서드로 필드 f를 즉시 변경하더라도 호출할 때까지는 시간 값을 다시 계산하지 않는다. set 메서드로 calendar 필드값을 변경하면, (*get(), getTime, 등) 호출해서 사용할 때 세팅된 필드값에 맞는 값을 반환한다.
[ 예제 ] {시작일자} {종료일자} 지정 후 날짜 List 출력
= > {현재} 로부터 {과거시점}까지 역순의 date List 출력해보기.
예시
startDate = 오늘 (2023-05-11)
endDate = 종료날짜 (2023-02-01)
// 종료날짜는 원하는 날짜를 세팅. (로직에 따라 2월의 첫째날일수도 있고, 1월의 마지막날 일 수도 있고...)
결과
2023-05-11
2023-05-10
2023-05-09
...
2023-02-01
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
public class DateTest {
@Test
public void dateTest() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 날짜 포맷 지정
// 날짜구하는 방법 (1) LocalDate 로 오늘 날짜 구하기
LocalDate now = LocalDate.now();
int year = now.getYear();
int monthValue = now.getMonthValue();
// 날짜구하는 방법 (2) Calendar로 오늘 날짜 구하기
Calendar cal = Calendar.getInstance(); // 현재 date,time 반환
String today = dateFormat.format(cal.getTime());
// *set 메소드 : set(int year, int month, int date)
// 어떤 값을 set 하는지에 따라서 getTime()시 값이 달라짐.
// 아래 코드는 2023 05 01 세팅
cal.set (year, Calendar.DATE -1, 1); // month는 사람기준 -1해줘야 원하는 달이 나옴.
String firstDay = dateFormat.format(cal.getTime()); // 이번달의 첫번째 날 구하기
String lastDay = String.valueOf(now.with(now.getMonth()).with(lastDayOfMonth())); // 이번달의 마지막 날 구하기
System.out.println("today : " + today);
System.out.println("firstDay : " + firstDay);
System.out.println("lastDay : " + lastDay);
// 오늘 날짜를 Calendar 에 세팅
int day = now.getDayOfMonth();
System.out.println("day : " + day);
// 오늘 날짜 파라미터로 세팅
cal.set(year, Calendar.DATE-1, day);
String startDate = dateFormat.format(cal.getTime());
String endDate = "2023-02-01"; // 테스트 위한 날짜
int i = 0;
List<String> dateList = new ArrayList<>();
while(!startDate.equals(endDate)){ // 다르면 실행, 동일 하다면 빠져나감
if(i==0) {
dateList.add(startDate);
}
// cal.add(Calendar.MONTH, 1); //1달 더해줌
cal.add(Calendar.DATE, -1); //1일 더해줌
startDate = dateFormat.format(cal.getTime()); //비교를 위한 값 셋팅
dateList.add(startDate);
//+1달 출력
// System.out.println(dateFormat.format(cal.getTime()));
i++;
}
for (String string : dateList) {
System.out.println(string);
}
}
}
'BackEnd > JAVA' 카테고리의 다른 글
서블릿 컨테이너의 ServletContext 동작 방식 / HttpSession (1) | 2025.01.20 |
---|---|
[JAVA] Thread pool 을 위한 ExecutorService 의 생성과 submit, shutdown (0) | 2024.11.13 |
[JAVA] POJO (Plain Old Java Object) (0) | 2023.03.07 |
[JAVA] 콤마로 구분되어 저장된 String 데이터 List화 하기 (0) | 2023.02.21 |
[JAVA] 클래스(class)와 생성자 (1) | 2023.01.14 |