Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

자바(Java) 8에서 현재 날짜·시간 가져오는 3가지 방법

자바(Java)에서 현재 날짜와 시간을 가져오려면 어떻게 해야 할까요? 이 글에서는 Java 8에서 활용할 수 있는 세 가지 방법을 코드 예제와 함께 소개합니다.

Java 8부터 도입된 java.time 패키지는 기존의 Date, Calendar API보다 직관적이며 불변(immutable)이라 스레드에 안전하다는 장점이 있습니다. 날짜와 시간을 다룰 때 핵심이 되는 클래스는 LocalDate, LocalTime, LocalDateTime입니다.

현재 날짜 가져오기

LocalDate 클래스는 연·월·일로 구성된 날짜를 표현할 때 사용합니다.

GetCurrentDate.java

import java.time.LocalDate;

public class GetCurrentDate {

    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        System.out.println(now.toString());
    }
}

실행 결과:

2020-02-07

날짜 형식 지정하기

DateTimeFormatter 클래스를 사용하면 날짜 표시 형식을 원하는 대로 바꿀 수 있습니다. 예를 들어 현재 날짜를 yyyy/MM/dd 형식으로 출력하려면 다음과 같이 작성합니다.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class GetCurrentDate {

    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        System.out.println(now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
    }
}

실행 결과:

2020/02/07

LocalDate 클래스에는 현재 날짜에 대한 더 자세한 정보를 얻을 수 있는 메서드도 마련되어 있습니다. 요일은 getDayOfWeek(), 해당 월의 몇 번째 날인지는 getDayOfMonth(), 해당 연도의 몇 번째 날인지는 getDayOfYear()로 조회할 수 있습니다.

import java.time.LocalDate;

public class GetCurrentDate {

    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        System.out.println("Today's date: " + now.toString());
        System.out.println("Day of week: " + now.getDayOfWeek().toString());
        System.out.println("Day of month: " + now.getDayOfMonth());
        System.out.println("Day of year: " + now.getDayOfYear());
    }
}

실행 결과:

Today's date: 2020-02-07
Day of week: FRIDAY
Day of month: 7
Day of year: 38

현재 시간 가져오기

LocalTime 클래스는 시각(시·분·초)을 표현할 때 사용합니다.

GetCurrentTime.java

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class GetCurrentTime {

    public static void main(String[] args) {
        LocalTime now = LocalTime.now();
        System.out.println("Time now: " + now.toString());
        System.out.println("Formatted time: " + now.format(DateTimeFormatter.ofPattern("HH:mm:ss")));
    }
}

참고: DateTimeFormatter를 사용하면 시간 역시 원하는 형식으로 출력할 수 있습니다.

실행 결과:

Time now: 00:02:53.313
Formatted time: 00:02:53

LocalTime 클래스에도 현재 시간의 세부 정보를 손쉽게 확인할 수 있는 유틸리티 메서드가 제공됩니다.

import java.time.LocalTime;

public class GetCurrentTime {

    public static void main(String[] args) {
        LocalTime now = LocalTime.now();
        System.out.println("Current hour: " + now.getHour());
        System.out.println("Current minute: " + now.getMinute());
        System.out.println("Current second: " + now.getSecond());
    }
}

실행 결과:

Current hour: 0
Current minute: 10
Current second: 16

현재 날짜 및 시간 함께 가져오기

현재 날짜 시간을 한 번에 가져오려면 LocalDateTime 클래스를 사용하면 됩니다.

package io.devqa.tutorials;

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

public class GetCurrentTime {

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd - HH:mm:ss")));
        System.out.println("Day of month: " + now.getDayOfMonth());
        System.out.println("Current hour: " + now.getHour());
    }
}

실행 결과:

2020/02/08 - 00:18:12
Day of month: 8
Current hour: 0

정리하면, 날짜만 필요하면 LocalDate, 시간만 필요하면 LocalTime, 두 정보를 모두 다뤄야 한다면 LocalDateTime을 사용하면 됩니다. 각 클래스는 DateTimeFormatter와 조합하여 다양한 형식으로 손쉽게 출력할 수 있으니 실무에서 적극 활용해 보시기 바랍니다.