SeouliteLab

[Java/자바] LocalDate, LocalDateTime 시간 날짜 변경하기 본문

프로그래밍

[Java/자바] LocalDate, LocalDateTime 시간 날짜 변경하기

Seoulite Lab 2024. 3. 8. 09:05

예제 1: LocalDate에서 일 수 더하기/빼기

// 현재 날짜
LocalDate today = LocalDate.now();
// 3일 후 날짜
LocalDate threeDaysLater = today.plusDays(3);
System.out.println("3일 후 날짜: " + threeDaysLater);
// 1달 전 날짜
LocalDate oneMonthAgo = today.minusMonths(1);
System.out.println("1달 전 날짜: " + oneMonthAgo);

`LocalDate`를 사용하여 날짜에 대한 연산을 수행하는 예제입니다. `plusDays()` 및 `minusMonths()` 메서드를 사용하여 날짜를 더하거나 빼는 방법을 보여줍니다.

예제 2: LocalDateTime에서 시간 더하기/빼기

// 현재 날짜와 시간
LocalDateTime now = LocalDateTime.now();
// 2시간 후
LocalDateTime twoHoursLater = now.plusHours(2);
System.out.println("2시간 후: " + twoHoursLater);
// 30분 전
LocalDateTime thirtyMinutesBefore = now.minusMinutes(30);
System.out.println("30분 전: " + thirtyMinutesBefore);

`LocalDateTime`을 사용하여 날짜와 시간에 대한 연산을 수행하는 예제입니다. `plusHours()` 및 `minusMinutes()` 메서드를 사용하여 시간을 더하거나 빼는 방법을 보여줍니다.

예제 3: 특정 날짜/시간으로 변경하기

// 2023년 12월 25일로 변경
LocalDate christmasDay = LocalDate.of(2023, 12, 25);
System.out.println("크리스마스: " + christmasDay);
// 15시 30분으로 변경
LocalDateTime specificTime = LocalDateTime.of(2023, 12, 25, 15, 30);
System.out.println("특정 시간: " + specificTime);

`LocalDate.of()` 및 `LocalDateTime.of()`를 사용하여 특정 날짜나 시간으로 변경하는 예제입니다. 각각의 메서드를 사용하여 원하는 날짜 또는 시간으로 객체를 생성합니다.

예제 4: 시간대(Timezone) 변경

// 서울 시간대로 변경
ZoneId seoulZone = ZoneId.of("Asia/Seoul");
ZonedDateTime seoulTime = ZonedDateTime.of(LocalDateTime.now(), seoulZone);
System.out.println("서울 현재 시간: " + seoulTime);
// 뉴욕 시간대로 변경
ZoneId newYorkZone = ZoneId.of("America/New_York");
ZonedDateTime newYorkTime = ZonedDateTime.of(LocalDateTime.now(), newYorkZone);
System.out.println("뉴욕 현재 시간: " + newYorkTime);

`ZoneId.of()` 및 `ZonedDateTime.of()`를 사용하여 시간대를 변경하는 예제입니다. 서울과 뉴욕의 현재 시간을 구하는 방법을 보여줍니다.

예제 5: 날짜 비교

LocalDate date1 = LocalDate.of(2023, 4, 15);
LocalDate date2 = LocalDate.of(2023, 4, 20);
if (date1.isBefore(date2)) {
    System.out.println(date1 + "은(는) " + date2 + "보다 이전입니다.");
} else if (date1.isAfter(date2)) {
    System.out.println(date1 + "은(는) " +

 date2 + "보다 이후입니다.");
} else {
    System.out.println(date1 + "과(와) " + date2 + "은(는) 같은 날짜입니다.");
}

`isBefore()`, `isAfter()`, `isEqual()` 메서드를 사용하여 날짜를 비교하는 예제입니다. 두 날짜를 비교하고 그 결과를 출력합니다.

예제 6: 날짜 포맷 변경

// 현재 날짜와 시간을 "yyyy-MM-dd HH:mm:ss" 포맷으로 변경
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = LocalDateTime.now().format(formatter);
System.out.println("현재 날짜와 시간: " + formattedDateTime);

`DateTimeFormatter.ofPattern()`을 사용하여 날짜 포맷을 변경하는 예제입니다. 현재 날짜와 시간을 원하는 포맷으로 출력합니다.