슬기로운 개발생활

[Java] 현재 날짜, 시간 구하기 (SimpleDateFormat, DateTimeFormatter)

by coco3o
반응형

자바에서 현재 날짜와 시간을 구하는 방법은 여러가지가 있다.

 

Java 8 이전

  • Date 객체 사용
  • Calendar 클래스의 getInstance() 메소드 사용
  • System 클래스의 currentTimeMillis() 메소드 사용
  • 원하는 포맷의 문자열로 변환 SimpleDateFormat 사용

Java 8 이후

  • java.time.LocalDate
  • java.time.LocalTime
  • java.time.LocalDateTime
  • 원하는 포맷의 문자열로 변환 DateTimeFormatter 사용

Date, Calendar 클래스는 문제가 많아 부분적으로 deprecated 되며 사용이 지양되고 있고,

Java 8 이후에 새롭게 만들어진 java.time 패키지 클래스 사용을 권장한다.

 

참고


Java 8 이전

SimpleDateFormat

다음 표는 SimpleDateFormat의 패턴 작성에 사용되는 기호들이다.

문자 의미
y
M
d
D 월 구분이 없는 일(1~365)
E 요일
h 시(1~12)
H 시(0~23)
m
s
S 밀리세컨드(1/1000초)
a 오전/오후
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy년 MM월 dd일");​

위의 두 개의 포맷을 사용해 아래의 세 가지 방법에 활용해본다.

Date() 객체 사용

 

Date()객체는 기본적으로 toString()을 사용한다.

public class TimeExample {
    public static void main(String[] args) {
        Date now = new Date();
        String nowTime = now.toString();
        System.out.println(nowTime);
    }
}
Sat May 01 11:55:16 KST 2021

Process finished with exit code 0

 

여기서 우리에게 맞는, 특정 문자열 포맷으로 얻고싶을 때 아래와 같이 사용한다.

public class TimeExample {
    public static void main(String[] args) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy년 MM월 dd일");

        Date now = new Date();

        String nowTime1 = sdf1.format(now);
        String nowTime2 = sdf2.format(now);

        System.out.println(nowTime1);
        System.out.println(nowTime2);
        
        //바로 출력도 가능
        //System.out.println(sdf1.format(now));
        //System.out.println(sdf2.format(now));
    }
}
2021-05-01 11:57:10
2021년 05월 01일

Process finished with exit code 0

Calendar 클래스의 getInstance() 메소드 사용

Calendar 클래스는 추상(abstract)클래스이므로 new 연산자를 사용해서 인스턴스를 생성할 수 없다.

 

그 이유는 날짜와 시간을 계산하는 방법이 지역과 문화, 나라에 따라 다르기 때문이다.

 

우리나라만 해도 양력과 음력이 동시에 사용되고 있다.

 

특별한 경우가 아니라면 Calendar 클래스의 정적 메소드인 getInstance() 메소드를 사용하자.

 

getInstance() 메소드는 현재 운영체제에 설정되어 있는 시간(TimeZone)을 기준으로 한다.

 

Calendar now = Calendar.getInstance();

 

Calendar 객체를 얻었다면 get() 메소드를 이용해서 날짜와 시간에 대한 정보를 읽을 수 있다.

 

Calendar now = getInstance();

int year = now.get(Calendar.YEAR);

int month = now.get(Calendar.MONTH) +1;

int day = now.get(Calendar.DAY_OF_MONTH);

int week = now.get(Calendar.DAY_OF_WEEK);

int amPm = now.get(Calendar.AM_PM);

int hour = now.get(Calendar.HOUR);

int minute = now.get(Calendar.MINUTE);

int second = now.get(Calendar.SECOND);

 

get() 메소드를 호출할 때 사용한 매개값은 모두 Calendar 클래스에 선언되어 있는 상수들이다.

 

SimpleDataFormat를 사용하여 간단하게 이용

public class TimeExample {
    public static void main(String[] args) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy년 MM월 dd일");

        Calendar now = Calendar.getInstance();

        String nowTime1 = sdf1.format(now.getTime());
        String nowTime2 = sdf2.format(now.getTime());

        System.out.println(nowTime1);
        System.out.println(nowTime2);
        
        //바로 출력도 가능
        //System.out.println(sdf1.format(now.getTime());
        //System.out.println(sdf2.format(now.getTime());
    }
}
2021-05-01 12:16:08
2021년 05월 01일

Process finished with exit code 0

System 클래스의 currentTimeMillis() 메소드 사용

public class TimeExample {
    public static void main(String[] args) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy년 MM월 dd일");

        String nowTime1 = sdf1.format(System.currentTimeMillis());
        String nowTime2 = sdf2.format(System.currentTimeMillis());

        System.out.println(nowTime1);
        System.out.println(nowTime2);
        
        //바로 출력도 가능
        //System.out.println(sdf1.format(System.currentTimeMillis());
        //System.out.println(sdf2.format(System.currentTimeMillis());
    }
}
2021-05-01 12:20:31
2021년 05월 01일

Process finished with exit code 0

Java 8 이후

java.time.LocalDate

LocalDate 클래스는 날짜를 표현하는 클래스이다.

public class TimeExample {
    public static void main(String[] args) {

	// 현재 날짜 구하기
	LocalDate now = LocalDate.now();
	
        // 현재 날짜 구하기(paris)
	LocalDate parisNow = LocalDate.now(ZoneId.of("Europe/Paris"));

	// 결과 출력
	System.out.println(now); // 2021-12-02
	System.out.println(parisNow); // 2021-12-01
 }
}

LocalDate.now();

- 현재 날짜를 가져온다.

 

LocalDate.now(ZoneId.of("Europe/Paris"));

날짜를 Europe/Paris의 타임존을 적용해 가져온다.

 

LocalDate 포맷 적용하기

public class TimeExample {
    public static void main(String[] args) {

        // 현재 날짜 구하기
        LocalDate now = LocalDate.now();
        // 포맷 정의
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        // 포맷 적용
        String formatedNow = now.format(formatter);
        // 결과 출력
        System.out.println(formatedNow); // 2021/12/02
    }
}

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

now.format(formatter);

- DateTimeFormatter 클래스를 이용해 원하는 포맷의 문자열로 출력할 수 있다.

 

년, 월(문자열, 숫자), 일, 요일, 일(Year 기준) 출력

public class TimeExample {
    public static void main(String[] args) {
        // 현재 날짜 구하기
        LocalDate now = LocalDate.now();
        // 연도, 월(문자열, 숫자), 일, 일(year 기준), 요일(문자열, 숫자)
        int year = now.getYear();
        String month = now.getMonth().toString();
        int monthValue = now.getMonthValue();
        int dayOfMonth = now.getDayOfMonth();
        int dayOfYear = now.getDayOfYear();
        String dayOfWeek = now.getDayOfWeek().toString();
        int dayOfWeekValue = now.getDayOfWeek().getValue();
        // 결과 출력
        System.out.println(now); // 2021-12-02
        System.out.println(year); // 2021
        System.out.println(month + "(" + monthValue + ")"); // DECEMBER(12)
        System.out.println(dayOfMonth); // 2
        System.out.println(dayOfYear); // 336
        System.out.println(dayOfWeek + "(" + dayOfWeekValue + ")"); // THURSDAY(4)
    }
}

int year = now.getYear();

- 현재 년도를 가져온다.

 

String month = now.getMonth().toString();

- 해당 월을 가져온다. 리턴받은 Month 객체의 toString() 메소드를 이용하면 월의 이름을 출력하고,

getValue()를 사용하면 숫자로 출력한다.

 

int monthValue = now.getMonthValue();

- 해당 월을 숫자로 표현하기 위해 now.getMonth().getValue()를 사용할 수도 있지만,

LocalDate 객체의 getMonthValue() 메소드를 사용할 수도 있다.

 

int dayOfMonth = now.getDayOfMonth();

- 월의 몇번째 날짜인지를 int로 나타낸다.


int dayOfYear = now.getDayOfYear();

- 년의 몇번째 날짜인지를 int로 나타낸다.


String dayOfWeek = now.getDayOfWeek().toString();

- getDayOfWeek() 메소드는 요일을 나타낸다.

그리고, DayOfWeek 객체의 toString() 메소드를 사용하여, 요일을 텍스트로 출력한다.

 

int dayOfWeekValue = now.getDayOfWeek().getValue();

- DayOfWeek 객체의 getValue() 메소드를 사용해 요일을 숫자로 변환한다.

월요일 (1) ~ 일요일(7)을 리턴한다.


java.time.LocalTime

LocalTime 클래스는 시간을 표현하는 클래스이다.

public class TimeExample {
    public static void main(String[] args) {
        
        // 현재 시간
        LocalTime now = LocalTime.now();
    	// 현재시간 출력
        System.out.println(now); // 18:03:47.904032
    	// 포맷 정의하기
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH시 mm분 ss초");
    	// 포맷 적용하기
        String formatedNow = now.format(formatter);
    	// 포맷 적용된 현재 시간 출력
        System.out.println(formatedNow); // 18시 03분 47초
    }
}

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH시 mm분 ss초");

- Date 예제와 마찬가지로 DateTimeFormatter 클래스를 이용해 원하는 포맷의 문자열로 변환할 수 있다.

 

현재 시간 구하기(시, 분, 초)

public class TimeExample {
    public static void main(String[] args) {
        
        // 현재 시간
        LocalTime now = LocalTime.now();
        // 현재시간 출력
        System.out.println(now); // 18:15:30.193857300
        // 시, 분, 초 구하기
        int hour = now.getHour();
        int minute = now.getMinute();
        int second = now.getSecond();
        // 시, 분, 초 출력
        System.out.println(hour); // 18
        System.out.println(minute); // 15
        System.out.println(second); // 30
    }
}

int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();

- getHour(), getMinute(), getSecond() 메소드를 이용해 시, 분, 초를 각각 구할 수 있다.


java.time.LocalDateTime

java.time.LocalDateTime 클래스는 날짜와 시간을 표현하는 클래스이다. (LocalDate와 LocalTime을 합친 클래스)

public class TimeExample {
    public static void main(String[] args) {

        // 현재 날짜/시간
        LocalDateTime now = LocalDateTime.now();
        // 현재 날짜/시간 출력
        System.out.println(now); // 2021-12-02T18:19:36.897421300
        // 포맷팅
        String formatedNow = now.format(DateTimeFormatter.ofPattern("yyyy년 MM월 dd일 HH시 mm분 ss초"));
        // 포맷팅 현재 날짜/시간 출력
        System.out.println(formatedNow); // 2021년 12월 02일 18시 19분 36초
    }
}

LocalDate, LocalTime 클래스에서 년, 월, 일, 요일, 시, 분, 초를 각각 구했던 것 처럼

LocalDateTime 클래스의 메소드를 이용해서 전부 구할 수 있다.

반응형

블로그의 정보

슬기로운 개발생활

coco3o

활동하기