Calendar / LocalDateTime
Java에서는 날짜와 시간을 처리할 수 있는 3가지 클래스를 제공한다.
Calendar
날짜를 제어하는 클래스
public static void main(String[] args) {
// Calendar 인스턴스 가져오기
// 대표적인 Singleton Pattern
Calendar nowCal = Calendar.getInstance();
// 현재 연월일 시분초 조회하기
System.out.println(nowCal.get(Calendar.YEAR));
System.out.println(nowCal.get(Calendar.MONTH) + 1);
System.out.println(nowCal.get(Calendar.DAY_OF_MONTH));
System.out.println(nowCal.get(Calendar.HOUR));
System.out.println(nowCal.get(Calendar.MINUTE));
System.out.println(nowCal.get(Calendar.SECOND));
// 1(일요일) ~ 7(토요일)
System.out.println(nowCal.get(Calendar.DAY_OF_WEEK));
}
public static void main(String[] args) {
// 현재 연월일만 문자열로 가져오기
// 현재 날짜/시간
Date now = Calendar.getInstance().getTime();
System.out.println(now);
// 날짜 포멧 지정
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 날짜를 포멧에 맞춰 변경
String formatDate = format.format(now);
// 출력
System.out.println(formatDate);
}
// Calendar 인스턴스 가져오기
Calendar nowCal = Calendar.getInstance();
// 날짜를 지정. (2022년 2월 1일)
nowCal.set(2022, 01, 01);
// 날짜에 10일 더하기
nowCal.add(Calendar.DAY_OF_MONTH, 10);
// 날짜에 20일 빼기
nowCal.add(Calendar.DAY_OF_MONTH, -20);
LocalDateTime
// 날짜 조회
public static void main(String[] args) {
LocalDate nowDate = LocalDate.now();
DateTimeFormatter dateFormatter =
DateTimeFormatter.ofPattern("yyyy년 MM읠 dd일");
String strNowDate = dateFormatter.format(nowDate);
System.out.println(nowDate);
System.out.println(strNowDate);
}
// 시간 조회
public static void main(String[] args) {
LocalTime nowTime = LocalTime.now();
DateTimeFormatter timeFormatter =
DateTimeFormatter.ofPattern("HH시 mm분 ss초");
String strNowTime = timeFormatter.format(nowTime);
System.out.println(nowTime);
System.out.println(strNowTime);
}
// 날짜와 시간 조회
public static void main(String[] args) {
LocalDateTime nowDateTime = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String strNowDateTime = dateTimeFormatter.format(nowDateTime);
System.out.println(nowDateTime);
System.out.println(strNowDateTime);
}
// 날짜와 날짜사이의 차이 구하기
LocalDate startDate = LocalDate.of(2022, 1, 1);
LocalDate endDate = LocalDate.of(2023, 5, 20);
Period between = Period.between(startDate, endDate);
System.out.println(between.getYears() + ","
+ between.getMonths() + ","
+ between.getDays());
LocalDate now = LocalDate.now();
System.out.println(now.getDayOfWeek().name()); // LocalDate, LocalDateTime 사용
YearMonth yearMonth = YearMonth.from(now);
// 이번 달의 첫 번째 날 구하기
LocalDate firstDay = yearMonth.atDay(1); // LocalDate, LocalDateTime 사용
System.out.println(firstDay);
System.out.println(firstDay.getDayOfWeek().name());
// 이번 달의 마지막 날 구하기
LocalDate lastDay = yearMonth.atEndOfMonth(); // LocalDate, LocalDateTime 사용
System.out.println(lastDay);
System.out.println(lastDay.getDayOfWeek().name());
// 이번 달은 총 며칠인지 구하기
int lengthOfDays = now.lengthOfMonth(); // LocalDate 전용
System.out.println(lengthOfDays);
// 이번 해는 총 며칠인지 구하기
int lengthOfYears = now.lengthOfYear(); // LocalDate 전용
System.out.println(lengthOfYears);
/**
* 가장 가까운 다음 영업일을 구한다.
* @param localDate 오늘
* @return
*/
public static Map<String, Object> getClosestWorkingDay(LocalDate localDate) {
// 1. localDate에 하루를 더한다.
localDate = localDate.plusDays(1);
// 2. 오늘의 요일을 구한다.
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
int dayCount = 1;
// 3. 하루를 더한 날짜가 휴일인지 검사한다.
while(dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) {
// 4. 만약 휴일이라면 하루를 또 더한다.
localDate = localDate.plusDays(1);
dayOfWeek = localDate.getDayOfWeek();
dayCount++;
}
Map<String, Object> result = new HashMap<>();
result.put("workingDay", localDate);
result.put("dayCount", dayCount);
// 5. 만약 휴일이 아니라면 더한 결과를 반환한다.
return result;
}
public static void main(String[] args) {
Map<String, Object> closestWorkingDay = getClosestWorkingDay(LocalDate.now());
System.out.println(closestWorkingDay.get("workingDay"));
System.out.println(closestWorkingDay.get("dayCount"));
closestWorkingDay = getClosestWorkingDay(LocalDate.of(2024, 2, 9)); // 금요일
System.out.println(closestWorkingDay.get("workingDay"));
System.out.println(closestWorkingDay.get("dayCount"));
System.out.println("========================");
}
public class LocalDateExam {
/**
* 전달 받은 날짜의 첫 번째 날짜부터 마지막 날짜까지를 출력 (요일 포함)
* @param date 기준이 되는 날짜
*/
public static void printCalendar(LocalDate date) {
// date 인스턴스를 YearMonth로 변경
YearMonth yearMonth = YearMonth.from(date);
// 첫번째 날짜를 구한다
LocalDate firstDay = yearMonth.atDay(1);
// date 인스턴스의 월의 총 길이(며칠)을 구한다
int days = date.lengthOfMonth();
// 반복하여 날짜와 요일을 출력한다
System.out.println(firstDay);
System.out.println(firstDay.getDayOfWeek().name());
for(int i = 0; i < days - 1; i++) {
firstDay = firstDay.plusDays(1);
System.out.println(firstDay);
System.out.println(firstDay.getDayOfWeek().name());
}
System.out.println("========================");
}