본문 바로가기
DEV

[JAVA] 현재날짜, 시간 구하기

by 아노앤유노 2023. 6. 30.
반응형

java
현재날짜
현재시간
date

현재날짜, 현재시간 구하기

java.time.LocalDateTime 클래스를 사용하여 현재 날짜 및 시간을 가져옵니다. LocalDateTime.now() 메서드를 호출하여 현재 날짜 및 시간을 currentDateTime 변수에 저장합니다. 그런 다음 currentDateTime를 출력하여 현재 날짜 및 시간을 확인할 수 있습니다.

또한, DateTimeFormatter 클래스를 사용하여 날짜 및 시간을 원하는 형식으로 포맷팅할 수 있습니다. 위 예제에서는 "yyyy-MM-dd HH:mm:ss" 형식으로 날짜 및 시간을 포맷팅한 후 출력합니다.

마지막으로, LocalDateTime 객체의 메서드를 사용하여 현재 날짜 및 시간의 연도, 월, 일, 시간, 분, 초 등 개별 요소를 가져올 수도 있습니다. 위 예제에서는 getYear(), getMonthValue(), getDayOfMonth(), getHour(), getMinute(), getSecond() 메서드를 사용하여 각각의 요소를 가져와 출력합니다.

적절한 함수를 사용하면 원하는 시간 또는 커스텀시간을 추출해낼수있다.

반응형
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CurrentDateTimeExample {
    public static void main(String[] args) {
        // 현재 날짜 및 시간 가져오기
        LocalDateTime currentDateTime = LocalDateTime.now();
        
        // 현재 날짜 및 시간 출력 (기본 형식)
        System.out.println("현재 날짜 및 시간: " + currentDateTime);
        
        // 원하는 형식으로 현재 날짜 및 시간 출력
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);
        System.out.println("형식화된 날짜 및 시간: " + formattedDateTime);
        
        // 현재 날짜의 연도, 월, 일, 시간, 분, 초 등 개별 요소 가져오기
        int year = currentDateTime.getYear();
        int month = currentDateTime.getMonthValue();
        int day = currentDateTime.getDayOfMonth();
        int hour = currentDateTime.getHour();
        int minute = currentDateTime.getMinute();
        int second = currentDateTime.getSecond();
        
        //결과 출력
        System.out.println("연도 : " + year);
        System.out.println("월 : " + month);
        System.out.println("일 : " + day);
        System.out.println("시간 : " + hour);
        System.out.println("분 : " + minute);
        System.out.println("초 : " + second);
    }
}
반응형

'DEV' 카테고리의 다른 글

[JAVA] builder 사용하기  (0) 2023.06.30
[JAVA] spring security 사용하기  (0) 2023.06.30
[JAVA] spring json 사용하기  (0) 2023.06.30
[JAVA] spring model 사용하기  (0) 2023.06.30
[C++] Thread 란? + 예제  (0) 2023.06.30