1. 날짜, 시간 출력 / 형식 변환

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class Main {
    public static void main(String[] args) {
        System.out.println("now");
        LocalDate date = LocalDate.now();
        LocalTime time = LocalTime.now();
        LocalDateTime dateTime = LocalDateTime.now();

        System.out.println(date); // 2022-05-18
        System.out.println(time);  // 16:07:51.225
        System.out.println(dateTime); // 2022-05-18T16:07:51.225

        System.out.println("of() usage");
        LocalDate dateOf = LocalDate.of(2021,3,30);
        LocalTime timeOf = LocalTime.of(22,50,20);
        System.out.println(dateOf); // 2021-03-30
        System.out.println(timeOf); // 22:50:20
        
        System.out.println("===========================================================");

        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
        String shorFormat = formatter.format(LocalTime.now());
        System.out.println(shorFormat); // 오후 4:07

        DateTimeFormatter myFormatter1 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String myDate1 = myFormatter1.format(LocalDate.now());
        System.out.println(myDate1);  // 2022/05/18
        
        DateTimeFormatter myFormatter2 = DateTimeFormatter.ofPattern("yyyy년 MM월 dd일");
        String myDate2 = myFormatter2.format(LocalDate.now());
        System.out.println(myDate2); // 20022년 05월 18일
    }
}

형식 참조 문서 : https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

2. 날짜와 시간차이 계산

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class Main {
    public static void main(String[] args) {
     
        LocalDate today = LocalDate.now();
        LocalDate birthDay = LocalDate.of(2020,1,1);
        Period period = Period.between(today, birthDay);

        System.out.println(period.getMonths());  // -4  // 핸재 월 5월
        System.out.println(period.getDays());  // -17  // 현재 일 18일

    }
}

 

3. quiz

 // 현재시간 연/월/일 시:분 으로 나타내기
 DateTimeFormatter myFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd h:mm");
String now = myFormatter.format(LocalDateTime.now());
System.out.println(now); // 2022/05/18 4:32

+ Recent posts