본문 바로가기

프로그래밍/JAVA

[JAVA 이론] 날짜와 시간 & 형식화

Calendar와 Date

Caleandar는 추상클래스이기 때문에 직접 객체를 생성할 수 없고, 메서드를 통해서 완전히 구현된 클래스의 인스턴스를 얻어야 한다.

Calendar cal = new Calendar(); //에러!! 추상클래스는 인스턴스를 생성할 수 없다.

//OK, getInstance()메서드는 Calendar 클래스를 구현한 클래스의 인스턴스를 반환한다.
Calendar cal = Calendar.getInstance();

Calendar를 받아 완전히 구현한 클래스로 GregorianCalendar와 BuddhistCalendar(태국력)가 있다.  인스턴스를 직접 생성해서 사용하지 않고 이처럼 메서드를 통해서 인스턴스를 반환받게 하는 이유는 최소한의 변경으로 프로그램이 동작할 수 있도록 하기 위한 것이다.

 

Date와 Calendar간의 변화

//Calendar를 Date로 변환
Calendar calendar = Calendar.getInstance();
	...
Date date = new Date(calendar.getTimeInMillis());

//Date를 Calendar로 변환
Date date = new Date();
	...
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

 

Calendar클래스와 Date클래스의 생성자와 메서드

- java.lang.Date 클래스 참고

- java.lang.Calendar 클래스 참고

https://docs.oracle.com/javase/8/docs/api/index.html

 

Java Platform SE 8

 

docs.oracle.com

 

형식화

형식화 클래스는 형식화에 사용될 패턴을 정의하는데, 데이터를 정의된 패턴에 맞춰 형식화할 수 있을 뿐만 아니라 역으로 형식화된 데이터에서 원래의 데이터를 얻어낼 수도 있다.

 

1. DecimalFormat

형식화 클래스 중에서 숫자를 형식화 하는데 사용되는 것이다. DecimalFormat을 이용하면 숫자 데이터를 정수, 부동소수점, 금액 등의 다양한  형식으로 표현할 수 있드며, 반대로 일정한 형식의 텍스트 데이터를 숫자로 쉽게 변환하는 것도 가능하다.

double number = 1234567.89;
String Pattern = "0"; //# 0.0 #.# #E0 등이 있다
DecimalFormat df = new DecimalFormat(pattern);
df.format(number);

df.parse(String); //기호와 문자가 포함된 문자열을 숫자로 변환

 

- DecimalFormat클래스의 생성자와 메서드

java.text.DecimalFormat클래스 참고

 

2. SimpleDateFormat

날짜를 원하는 형태에 맞게 출력하는 클래스이다.

Date today = new Date();
simpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd"); //(y:년도), (M:월), (w:주), (d:일) 등 

String result = df.format(today); //오늘 날짜를 yyyy-MM-dd형태로 반환

/* ======================================================================= */
DateFormat df1 = new SimpleDateFormat("yyyy년 MM월 dd일");
DateFormat df2 = new SimpleDateFormat("yyyy/MM/dd");

try {
	Date d = df1.parse("2022년 02월 19일");
	System.out.println(df2.format(d)); //2022/02/19 출력
}catch(Exception e) {}

 

- SimpleDateFormat클래스의 생성자와 메서드

java.text.SimpleDateFormat클래스 참고

 

3. ChoiceFormat

특정 범위에 속하는 값을 문자열로 변환해주는 클래스이다.

double[] limits = {60, 70, 80, 90};
String[] grades = {"D", "C", "B", "A"};
int[] scores = {100, 70, 60};

ChoiceFormat form = new ChoiceFormat(limits, grades);
		
for(int i = 0; i < scores.length; i++) {
	System.out.println(scores[i] + ":" + form.format(scores[i])); //100:A 70:C 60:D
}


String pattern = "60#D|70#C|80<B|90#A";
int[] scores = {91, 88, 60};
		
ChoiceFormat form = new ChoiceFormat(pattern);
		
for(int i = 0; i < scores.length; i++) {
	System.out.println(scores[i] + ":" + form.format(scores[i])); //91:A 88:B 60:D
}

 

- ChoiceFormat클래스의 생성자와 메서드

java.text.ChoiceFormat클래스 참고

 

4. MessageFormat

데이터를 정해진 양식에 맞게 출력할 수 있도록 도와주는 클래스이다. 데이터가 들어갈 자리를 마련해 놓은 양식을 미리 작성하고 프로그램을 이용해서 다수의 데이터를 같은 양식으로 출력할 때 사용한다.

String msg = "Name: {0} Tel: {1} Age: {2} Birthday: {3}";
		
Object[] arguments = {
	"Tom", "010-1234-5678", "21", "2002-02-20"
};
		
String result = MessageFormat.format(msg, arguments);
System.out.println(result); //Name: Tom Tel: 010-1234-5678 Age: 21 Birthday: 2002-02-20

String contents = "Name: Tom Tel: 010-1234-5678 Age: 21 Birthday: 2002-02-20";
MessageFormat df = new MessageFormat(msg);
Object[] obj = df.parse(contents); //TOM 010-1234-5678 21 2002-02-20

 

java.time패키지

JDK1.8부터 Date와 Calendar의 단점을 해소하기 위해 java.time패키지가 추가 되었다. 패키지에 속한 클래스들은 String클래스처럼 immutable해서 Calendar의 thread-safe하지 않은 면을 보완해준다.

 

서브 패키지

java.time                          날짜와 시간을 다루는데 필요한 핵심 클래스들을 제공

java.time.chrono          표준(ISO)이 아닌 달력 시스템을 위한 클래스들을 제공

java.time.format           날짜와 시간을 파싱하고, 형상화하기 위한 클래스들을 제공

java.time.temporal      날짜와 시간의 필드(filed)와 단위(unit)를 위한 클래스들을 제공

java.time.zone               시간대(time-zone)와 관련된 클래스들을 제공

 

java.time패키지의 핵심 클래스

LocalDate               날짜

LocalTime              시간

LocalDateTime     날짜 + 시간

ZonedDateTime   날짜 + 시간 + 시간대

 

날짜 - 날짜 = Period

시간 - 시간 = duration

 

객체 생성하기

//now
LocalDate date = LocalDate.now(); //2022-02-21
LocalTime time = LocalTime.now(); //23:06:01.142

LocalDateTime localDateTime = LocalDateTime.now(); //2022-02-21T23:06:01.142
ZonedDateTime zonedDateTime = ZonedDateTime.now(); //2022-02-21T23:06:01.142+11:00[Asia/Seoul]

//of
LocalDate date = LocalDate.of(2022, 02, 21); //2022년 02월 21일
LocalTime time = LocalTime.of(23, 06, 01); //23시 06분 01초

 

Temporal, TemporalAccessor, TemporalAdjuster를 구현한 클래스

- LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Instant 등

 

TemporalAmount를 구현한 클래스

- Period, Duration

 

TemporalUnit   날짜와 시간의 단위를 정의해 놓은 인터페이스

ChronoUnit        TemporalUnit을 구현한 것

TemporalField  년, 월, 일 등 날짜와 시간의 필드를 정의해 놓은 것, 열거형 ChronoFeild가 이 인터페이스 구현

 

파싱과 포맷

날짜와 시간을 원하는 형식으로 출력하고 해석(파싱, parsing)하는 것

LocalDate date = LocalDate.of(2022,2,23);
String timeFormat = DateTimeFormatter.ISO_LOCAL_DATE.format(date); // "2022-02-23"
String timeFormat = date.format(DateTimeFormatter.ISO_LOCAL_DATE) // "2022-02-23"