IT/Java

[JAVA] 현재 시간 구하는 방법

binary? 2024. 5. 3. 08:43

 

[JAVA] 현재 시간 구하는 방법

 

프로젝트 진행하다가 현재 시간을 구해야 하는 경우가 생겼습니다.

 

아래 3줄을 이용해서 간단하게 구할 수 있습니다.

 

저는 아래와 같은 형식이 필요했기 때문에

yyyy-MM-dd HH:mm:ss

DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 이렇게 선언하였습니다.

 

다른 포맷을 원할 때에는 포맷형식만 바꿔주면 됩니다.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

// 출력 형식 지정
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// LocalDateTime 객체를 지정된 형식의 문자열로 변환
String formattedDateTime = now.format(formatter);

// 결과 출력
log.info("현재 시간: " + formattedDateTime);