JAVA 날짜와 시간 다루기

sung eon·2022년 5월 19일
0

JAVA

목록 보기
12/21

날짜/시간 다루기

현재시간 알고 싶을 때 .now

Sytem.out.println("now usages");
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();

Sytem.out.println(date);
Sytem.out.println(time);
Sytem.out.println(dateTime);

출력하면,

2022-05-18
00:13:52.736
2022-05-18T00:13:52.736


특정한 시간 지정해주고 싶을 때 .of

Sytem.out.println("now usages");
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();

Sytem.out.println(date);
Sytem.out.println(time);
Sytem.out.println(dateTime);

Sytem.out.println("of() usage");
LocalDate dateOf = LocalDate.of(2022, 3, 30);
LocalTime timeOf = LocalTime.of(22, 50, 0);

Sytem.out.println(dateOf);
Sytem.out.println(timeOf);

출력하면,

of() usage
2022-03-30
22:50


시간 날짜 형식을 년/월/일, 시/분/초로 바꾸고 싶을 때 DateTimeFormatter

DateTimeFormatter formatter = DateTimeFormatter.ifLocalizedTime(FormatStyle.SHORT);
Srting shortFormat = formatter.format(LocalTime.now());
Sytem.out.println(shortFormat);

출력하면,

오전 12:18


다른 format스타일

DateTimeFormatter myFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String myDate = myFormatter.format(LocalDate.now());
Sytem.out.println(myDate);

2022/05/18

yyyy년 MM월 dd일도 가능!


날짜나 시간의 기간 계산

LocalDate today = LocalDate.now();
LocalDate bday = LocalDate.of(2020, 3, 17)
Period period = Period.between(today, bday)
Sytem.out.println(period.getMonths());
//몇달이 지났는지
Sytem.out.println(period.getDays);
//며칠이 지났는지

-2
-1

profile
코베베

0개의 댓글