📗 Docs

[Java] LocalDate, LocalTime, LocalDateTime 정리

파일과 미디어
date
Apr 6, 2023
slug
Java-LocalDateTime
author
status
Public
tags
Java
Blog
summary
LocalDateTime 사용법
type
Post
thumbnail
category
📗 Docs
updatedAt
Apr 19, 2023 05:56 PM

Java 시간 API 시대 흐름

java.util.Date > java.util.Calendar > java.time(org.joda.time)
 

LocalDate 개념

  • 로컬 날짜 클래스로 날짜정보만 필요할 때 사용.
LocalDate currentDate = LocalDate.now();
// 작성기준 : 2023-04-04

LocalDate targetDate = LocalDate.of(2023,04,03);
// 결과 : 2023-04-03
 

LocalTime 개념

  • 로컬 시간 클래스로 시간 정보만 필요할 때 사용
// 로컬 컴퓨터의 현재 시간 정보를 저장한 LocalDate 객체를 리턴. 
LocalTime currentTime = LocalTime.now();   
// 작성기준 : 00:06:30

// 파라미터로 주어진 시간 정보를 저장한 LocalTime 객체를 리턴.
LocalTime targetTime = LocalTime.of(12,33,35,22); 
// 끝에 4번째 매개변수는 nanoSecond 인데 선택 값이다 굳이 쓰지 않아도 된다.
// 결과 : 12:32:33.0000022
 

LocalDateTime 개념

  • 날짜와 시간 정보 모두가 필요할 때 사용.
// 로컬 컴퓨터의 현재 날짜와 시간 정보
LocalDateTime currentDateTime = LocalDateTime.now();    
// 작성기준 : 20123-04-04T00:07:30.388

LocalDateTime targetDateTime = LocalDateTime.of(2019, 11, 12, 12, 32,22,3333);
// 여기도 second,nanoSecond 매개변수는 필수가 아닌 선택입니다.
// 결과 : 2019-11-12T12:32:22.000003333
 

날짜 더하기

LocalDateTime currentDateTime = LocalDateTime.now();
// 더 하기는 plus***() 빼기는 minus***()// currentDateTime.plusYears(long) or minusYears(long)
currentDateTime.plusDays(2)
// 결과 : 2023-04-06T12:32:22.000003333
리턴 타입
메소드(매개변수)
설명
java.time.LocalDateTime
plusYears()
java.time.LocalDateTime
plusMonths()
java.time.LocalDateTime
plusWeeks()
java.time.LocalDateTime
plusDays()
java.time.LocalDateTime
plusHours()
java.time.LocalDateTime
plusMinutes()
java.time.LocalDateTime
plusSeconds()
java.time.LocalDateTime
plusNanos()
밀리초
빼기도 동일합니다. minusYear(),minusMonths() …
 

LocalDate / YearMonth를 이용하여 특정 월의 일 수, 마지막 날 구하기!

//기준일자
LocalDate date = LocalDate.parse("2023-04-04");

//해당 월의 첫째 날
LocalDate firstDate = date.withDayOfMonth(1); // 2023-04-01

//해당 월의 마지막 날
LocalDate lastDate = date.withDayOfMonth(date.lengthOfMonth()); // 2023-04-30

//해당 요일;
DayOfWeek dayOfWeek = date.getDayOfWeek(); // THUSEDAY

//해당 요일 int value
dayOfWeek.getValue(); // 2
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

public class Main {

    public static void main(String[] args) {

        String novemberDate = "2019-11-09";
        
        /** 
        * YearMonth 객체 생성(from 함수로 LocalDate 객체를 파라미터로 넣어주면 된다)
        */
        YearMonth novemberYearMonth = YearMonth.from(LocalDate.parse(novemberDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        /**
         * 해당 월의 일 수(int)
         * */
        System.out.println(novemberYearMonth.lengthOfMonth()); // 30

        /**
         * 해당 월의 마지막 날(LocalDate)
         * */
        System.out.println(novemberYearMonth.atEndOfMonth()); // 2019-11-30
    }
}