Java API를 사용하여 현재 날짜, 현재 시간을 구하는 방법을 소개합니다.
Java 8 이후
- java.time.LocalDate
- java.time.LocalTime
- java.time.LocalDateTime
Java 8 이전
- java.util.Date
- java.util.Calendar
Java 8 이후
Java 8 이후부터는 java.time 패키지의 클래스들을 사용하여
날짜와 시간을 표현합니다.
그리고, java.time.format.DateTimeFormatter 클래스를 이용하여
날짜와 시간을 원하는 형식으로 출력할 수 있습니다.
1. java.time.LocalDate
java.time.LocalData 클래스는 날짜를 표현하는 클래스입니다.
현재 날짜(타임존 적용) 구하기
|
import java.time.LocalDate; |
|
import java.time.ZoneId; |
|
|
|
public class CurrentDateTime { |
|
public static void main(String[] args) { |
|
|
|
// 현재 날짜 구하기 (시스템 시계, 시스템 타임존) |
|
LocalDate now = LocalDate.now(); |
|
|
|
// 현재 날짜 구하기(Paris) |
|
LocalDate parisNow = LocalDate.now(ZoneId.of("Europe/Paris")); |
|
|
|
// 결과 출력 |
|
System.out.println(now); // 2021-06-17 |
|
System.out.println(parisNow); // 2021-06-16 |
|
} |
|
} |
LocalDate.now();
시스템에 default로 지정된 시간과 타임존을 이용하여 현재 날짜를 가져옵니다.
LocalDate.now(ZoneId.of("Europe/Paris"));
시스템 시계의 날짜를 Europe/Paris의 타임존을 적용하여 가져옵니다.
포맷 적용하기
|
import java.time.LocalDate; |
|
import java.time.format.DateTimeFormatter; |
|
|
|
public class CurrentDateTime { |
|
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/06/17 |
|
} |
|
} |
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
now.format(formatter);
DateTimeFormatter 클래스를 이용하여 원하는 형태로 출력할 수 있습니다.
년, 월(문자열, 숫자), 일, 요일, 일(Year 기준) 출력하기
|
import java.time.LocalDate; |
|
|
|
public class CurrentDateTime { |
|
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-06-17 |
|
System.out.println(year); // 2021 |
|
System.out.println(month + "(" + monthValue + ")"); // JUNE(6) |
|
System.out.println(dayOfMonth); // 17 |
|
System.out.println(dayOfYear); // 168 |
|
System.out.println(dayOfWeek + "(" + dayOfWeekValue + ")"); // THURSDAY(4) |
|
|
|
} |
|
} |
int year = now.getYear();
년도를 가져옵니다.
String month = now.getMonth().toString();
getMonth() 메소드는 해당월을 나타내는 java.time.Month Enum을 리턴합니다.
리턴받은 Month 객체의 toString() 메소드를 이용하여, 월의 이름을 출력하였습니다.
Month 객체를 사용하여, 월을 숫자로 출력하고 싶다면,
now.getMonth().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 Enum 객체를 리턴합니다.
그리고, DayOfWeek 객체의 toString() 메소드를 사용하여, 요일을 텍스트로 출력하였습니다.
int dayOfWeekValue = now.getDayOfWeek().getValue();
DayOfWeek 객체의 getValue() 메소드를 사용하여 요일을 숫자로 변환할 수 있습니다.
월요일(1) ~ 일요일(7)을 리턴합니다.
2. java.time.LocalTime
java.time.LocalTime 클래스는 시간을 표현하는 클래스입니다.
현재 시간 구하기, 포맷 적용
|
import java.time.LocalTime; |
|
import java.time.format.DateTimeFormatter; |
|
|
|
public class CurrentDateTime { |
|
public static void main(String[] args) { |
|
|
|
// 현재 시간 |
|
LocalTime now = LocalTime.now(); |
|
|
|
// 현재시간 출력 |
|
System.out.println(now); // 06:20:57.008731300 |
|
|
|
// 포맷 정의하기 |
|
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH시 mm분 ss초"); |
|
|
|
// 포맷 적용하기 |
|
String formatedNow = now.format(formatter); |
|
|
|
// 포맷 적용된 현재 시간 출력 |
|
System.out.println(formatedNow); // 06시 20분 57초 |
|
|
|
} |
|
} |
LocalTime.now();
LocalTime 클래스를 이용하여 현재 시간을 구할 수 있습니다.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH시 mm분 ss초");
String formatedNow = now.format(formatter);
LocalDate 예제와 마찬가지로 DateTimeFormatter 클래스를 이용하여
시간을 원하는 포맷의 문자열로 변환할 수 있습니다.
현재 시간의 시, 분, 초 구하기
|
import java.time.LocalTime; |
|
|
|
public class CurrentDateTime { |
|
public static void main(String[] args) { |
|
|
|
// 현재 시간 |
|
LocalTime now = LocalTime.now(); |
|
|
|
// 현재시간 출력 |
|
System.out.println(now); // 06:25:59.985969400 |
|
|
|
// 시, 분, 초 구하기 |
|
int hour = now.getHour(); |
|
int minute = now.getMinute(); |
|
int second = now.getSecond(); |
|
|
|
// 시, 분, 초 출력 |
|
System.out.println(hour); // 6 |
|
System.out.println(minute); // 25 |
|
System.out.println(second); // 59 |
|
|
|
} |
|
} |
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
getHour(), getMinute(), getSecond() 메소드를 이용하여
시, 분, 초를 각각 구할 수 있습니다.
3. java.time.LocalDateTime
java.time.LocalDateTime 클래스는 날짜와 시간을 표현하는 클래스입니다.
현재 날짜/시간 구하기, 포맷팅해서 출력하기
|
import java.time.LocalDateTime; |
|
import java.time.format.DateTimeFormatter; |
|
|
|
public class CurrentDateTime { |
|
public static void main(String[] args) { |
|
|
|
// 현재 날짜/시간 |
|
LocalDateTime now = LocalDateTime.now(); |
|
|
|
// 현재 날짜/시간 출력 |
|
System.out.println(now); // 2021-06-17T06:43:21.419878100 |
|
|
|
|
|
// 포맷팅 |
|
String formatedNow = now.format(DateTimeFormatter.ofPattern("yyyy년 MM월 dd일 HH시 mm분 ss초")); |
|
|
|
// 포맷팅 현재 날짜/시간 출력 |
|
System.out.println(formatedNow); // 2021년 06월 17일 06시 43분 21초 |
|
|
|
} |
|
} |
LocalDateTime.now();
LocalDateTime.now() 메소드를 사용하면
현재 날짜와 시간을 모두 구할 수 있습니다.
now.format(DateTimeFormatter.ofPattern("yyyy년 MM월 dd일 HH시 mm분 ss초"));
LocalDate, LocalTime 클래스의 결과를 포맷팅 했던 것과 마찬가지로
DateTimeFormatter 클래스를 이용해서 포맷팅 할 수 있습니다.
년, 월, 일, 요일, 시, 분, 초 각각 구하기
|
import java.time.LocalDateTime; |
|
|
|
public class CurrentDateTime { |
|
public static void main(String[] args) { |
|
|
|
// 현재 날짜/시간 |
|
LocalDateTime now = LocalDateTime.now(); |
|
|
|
// 현재 날짜/시간 출력 |
|
System.out.println(now); // 2021-06-17T06:40:35.477667600 |
|
|
|
|
|
// 년, 월(문자열, 숫자), 일(월 기준, 년 기준), 요일(문자열, 숫자), 시, 분, 초 구하기 |
|
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(); // 요일(숫자) |
|
int hour = now.getHour(); |
|
int minute = now.getMinute(); |
|
int second = now.getSecond(); |
|
|
|
// 년, 월(문자열, 숫자), 일(월 기준, 년 기준), 요일(문자열, 숫자), 시, 분, 초 출력 |
|
System.out.println("년 : " + year); // 년 : 2021 |
|
System.out.println("월 : " + month + "(" + monthValue + ")"); // 월 : JUNE(6) |
|
System.out.println("일(월기준) : " + dayOfMonth); // 일(월기준) : 17 |
|
System.out.println("일(년기준) : " + dayOfYear); // 일(년기준) : 168 |
|
System.out.println("요일 : " + dayOfWeek + "(" + dayOfWeekValue + ")"); // 요일 : THURSDAY(4) |
|
System.out.println("시간 : " + hour); // 시간 : 6 |
|
System.out.println("분 : " + minute); // 분 : 40 |
|
System.out.println("초 : " + second); // 초 : 35 |
|
|
|
} |
|
} |
LocalDate, LocalTime 클래스에서 년, 월, 일, 요일, 시, 분, 초를 각각 구했던 것처럼
LocalDateTime 클래스의 메소드를 이용해서 각각을 구할 수 있습니다.
Java 8 이전
Java 8 이전의 날짜와 시간을 나타내는 Date, Calendar 클래스는
많은 부분이 deprecated 되었고, 가능하면 사용을 권장하지 않습니다.
그래서 여기에서는 기본적인 내용만 소개합니다.
1. java.util.Date
|
import java.text.SimpleDateFormat; |
|
import java.util.Date; |
|
|
|
public class CurrentDateTime { |
|
public static void main(String[] args) { |
|
|
|
// 현재 날짜/시간 |
|
Date now = new Date(); |
|
|
|
// 현재 날짜/시간 출력 |
|
System.out.println(now); // Thu Jun 17 06:57:32 KST 2021 |
|
|
|
|
|
// 포맷팅 정의 |
|
SimpleDateFormat formatter = new SimpleDateFormat("yyyy년 MM월 dd일 HH시 mm분 ss초"); |
|
|
|
// 포맷팅 적용 |
|
String formatedNow = formatter.format(now); |
|
|
|
// 포맷팅 현재 날짜/시간 출력 |
|
System.out.println(formatedNow); // 2021년 06월 17일 06시 57분 32초 |
|
|
|
} |
|
} |
Date now = new Date();
Date 객체를 생성하여, 현재 시간을 구했습니다.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy년 MM월 dd일 HH시 mm분 ss초");
String formatedNow = formatter.format(now);
SimpleDateFormat 클래스를 이용해서,
원하는 포맷으로 문자열을 생성할 수 있습니다.
2. java.util.Calendar
|
import java.text.SimpleDateFormat; |
|
import java.util.Calendar; |
|
import java.util.Date; |
|
|
|
public class CurrentDateTime { |
|
public static void main(String[] args) { |
|
|
|
// 현재 날짜/시간 |
|
Date now = Calendar.getInstance().getTime(); |
|
|
|
// 현재 날짜/시간 출력 |
|
System.out.println(now); // Thu Jun 17 07:05:24 KST 2021 |
|
|
|
|
|
// 포맷팅 정의 |
|
SimpleDateFormat formatter = new SimpleDateFormat("yyyy년 MM월 dd일 HH시 mm분 ss초"); |
|
|
|
// 포맷팅 적용 |
|
String formatedNow = formatter.format(now); |
|
|
|
// 포맷팅 현재 날짜/시간 출력 |
|
System.out.println(formatedNow); // 2021년 06월 17일 07시 05분 24초 |
|
|
|
} |
|
} |
Calendar.getInstance().getTime();
Calendar의 instance를 생성하여, Calendar 객체의 getTime() 메소드를 호출하여 현재시간을 가져왔습니다.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy년 MM월 dd일 HH시 mm분 ss초");
String formatedNow = formatter.format(now);
getTime() 메소드가 리턴하는 객체가 Date 타입이기 때문에,
앞의 예제와 마찬가지로 SimpleDateFormat 클래스를 이용하여 포맷팅을 하였습니다.
Java API를 이용하여
현재 날짜, 시간을 구하고, 포맷팅 하는 방법을 알아보았습니다.
출처: https://hianna.tistory.com/607 [어제 오늘 내일]
'프로그래밍 언어 > Java' 카테고리의 다른 글
자바 공백문자 채우기 (0) | 2022.02.17 |
---|---|
자바 소수점 올림 / 버림 / 반올림/ 절대값 (0) | 2022.02.17 |
referece by call vs value by call (0) | 2022.02.17 |
객체지향 설계 원칙 5가지 (0) | 2022.02.08 |
Stream 사용 주의사항 (0) | 2022.02.02 |