본문 바로가기
Spring

[3] 자바 중급 문법 3 -- 날짜와 시간

by 민지기il 2025. 3. 21.

플젝하다보면 날짜를 다루는 경우가 꼭 있는데 그때마다 찾기 귀찮아서 정리해뒀다..

[1] 날짜와 시간 라이브러리

[2] 문제 1 --202411000초에서 12개월 34시간 후의 시각을 찾아라.

public class Test {
    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2024,01,01,0,0,0,0);
        LocalDateTime gap = time.plusYears(1).plusMonths(2).plusDays(3).plusHours(4);
        System.out.println("기준 시각: "+ time);
        System.out.println("이후 시각: "+ gap);
    }
}

[3] 문제 2 -- 202411일 부터 2주 간격으로 5번 반복하여 날짜를 출력하는 코드

public class Test {
    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2024,01,01,0,0,0,0);
        for(int i=1; i<=5; i++){
            LocalDateTime gap = time.plusDays(14*(i-1));
            System.out.println("날짜"+i+": "+gap);
        }
    }
}

[4] 문제 3 -- 남은 기간 출력 

ex) 시작 날짜: 2024-01-01

목표 날짜: 2024-11-21

남은 기간:0년 10개월 20일

디데이: 325일 남음

public class Test {
    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(2024, 1, 1);
        LocalDate endDate = LocalDate.of(2024, 11, 21);
        Period period = Period.between(startDate, endDate);
        long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);

        System.out.println("시작 날짜: "+ startDate);
        System.out.println("목표 날짜: "+ endDate);
        System.out.println("남은 기간:"+ period.getYears()+"년 " + period.getMonths()+"개월 "+period.getDays()+"일");
        System.out.println("디데이: "+ daysBetween+"일 남음");
    }
}

[5] 문제 4 -- 입력 받은 년도, 월의 첫날 요일과 마지막날 요일을 구해라

public class Test {
    public static void main(String[] args) {
        int year = 2024;
        int month = 1;
        LocalDate firstDay = LocalDate.of(year, month, 1);
        DayOfWeek firstDayOfWeek = firstDay.getDayOfWeek();

        LocalDate lastDay = firstDay.with(TemporalAdjusters.lastDayOfMonth());
        DayOfWeek lastDayOfWeek = lastDay.getDayOfWeek();

        System.out.println(year + "년 " + month + "월 1일의 요일: " + firstDayOfWeek);
        System.out.println(year + "년 " + month + "월 마지막 날의 요일: " + lastDayOfWeek);
    }
}

[6] 문제 5 -- ZoneDateTime

public class Test {
    public static void main(String[] args) {
        ZonedDateTime seoulTime = ZonedDateTime.of(LocalDate.of(2024, 1, 1),
                LocalTime.of(9, 0), ZoneId.of("Asia/Seoul"));
        ZonedDateTime londonTime =
                seoulTime.withZoneSameInstant(ZoneId.of("Europe/London"));
        ZonedDateTime nyTime =
                seoulTime.withZoneSameInstant(ZoneId.of("America/New_York"));
        System.out.println("서울의 회의 시간: " + seoulTime); System.out.println("런던의 회의 시간: " + londonTime); System.out.println("뉴욕의 회의 시간: " + nyTime);
    }
}

'Spring' 카테고리의 다른 글

[5] 자바 중급 문법 - ArrayList  (0) 2025.03.28
[4] 자바 중급 문법 - Generic  (0) 2025.03.26
[2] 자바 중급 문법 2  (0) 2025.03.21
[1] 자바 중급 문법 1  (0) 2025.03.19
[8] 소셜 로그인 구현 2  (0) 2025.03.18