⭐Java.time 패키지
시간과 관련된 클래스들을 모아뒀다.

java1.1때 만들어진 Date, Calendar 클래스는
여러 문제점을 안고 있었다.

이에 따라 java8에서 새로운 클래스들이 만들어졌다.

java.time의 주요 클래스


LocalDate 날짜만

LocalTime 시간만
LocalDateTime 날짜 + 시간
Period 날짜 간격
Duration 시간 간격

 

예제)

구버전 시간 클래스

Date now = new Date();
System.out.println("현재시간" + now);

//Calendar cal = new Calendar(); //new 못때리게 개발자가 막아놨다.
Calendar cal = Calendar.getInstance();
cal.set(2025,4,14); //0부터 시작(4= 5월)
System.out.println("설정날짜"+ cal.getTime());

 

예제2)

특정날짜의 요일 확인

//2000년 5월13일이 무슨 요일일까?
LocalDate birthday = LocalDate.of(2000, 5, 13);
System.out.println("00-05-13요일"+birthday.getDayOfWeek());

 

예제3)

100일 후 날짜 계산

//현재 날짜로부터 100일 후의 날짜는?
LocalDate now = LocalDate.now();
LocalDate after100 = now.plusDays(100);
System.out.println("100일후"+after100);

 

예제4)

나이 계산

//나이계산하기
LocalDate birth = LocalDate.of(2000, 5, 13);
LocalDate today = LocalDate.now();

//기간계산
Period age = Period.between(birth, today);

//나이를 연도 단위로 추출
System.out.println("나이는" + age.getYears());

 

예제5)

시간 차이 계산

LocalTime start = LocalTime.of(9, 0); //오전 9시
LocalTime end = LocalTime.of(11, 30); //오전 11:30

Duration dr = Duration.between(start, end);
System.out.println("시차는" + dr.toHours()+"시간");
System.out.println("시차는" + dr.toMinutes()+"분");
System.out.println("시차는" + dr.toSeconds()+"초");

LocalDate election = LocalDate.of(2025, 6, 3);
System.out.println(election.getDayOfWeek());

 

예제6)

시간 표시방식 변경

LocalDateTime now = LocalDateTime.now();
System.out.println("현재일시"+now);
//2025-05-14T10:02:13
/*
이걸 한국식 날짜포맷으로 바꿀 수는 없을까?

2025년 05월 14일 12시 00분
이런 식으로 패턴을 지정할 수 있다.

yyyy 4자리 년
mm 2자리 월
dd 2자리 일
hh 2자리 시간
mm 2자리 분

DateTimeFormatter
 */
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy년 MM월dd일 HH시mm분");
now.format(dtf);
//내가 정의한 포맷으로 현재 시간을 표시해준다.
System.out.println("현재일시" + now.format(dtf));

 

+ Recent posts