Language/Java

7. 날짜, 시간 & 형식화

리져니 2021. 7. 19. 21:20

Date 클래스

날짜와 시간을 다룰 목적으로 제공됨

Date d = new Date();처럼 인스턴스를 생성하여 사용한다

 

Calendar클래스

추상 클래스로 직접 객체를 생성할수 없고, 메서드를 통해서 완전히 구현된 클래스의 인스턴스를 얻어야함

Calendar cal = Calendar.getInstance();

* getInstance()는 시스템의 국가와 지역설정을 확인해서 태국인 경우에는 BuddhistCalendar의 인스턴스를 반환, 그 외에는 GregorianCalendar의 인스턴스를 반황한다

* 메서드를 통해 인스턴스를 반환하는 것은, 최소한의 변경으로 프로그램이 동작하도록 하기 위함이다.

 

public class Main {
    public static void main(String[] args) throws IOException {
        Calendar c = Calendar.getInstance();
        System.out.println(c.get(Calendar.MONDAY)+"/"+ c.get(Calendar.DATE));
        }
    }

실행 결과:

 

- 날짜와 시간을 원하느 값으로 변경하려면 set메서드를 사용하면 된다.

public class Main {
    public static void main(String[] args) throws IOException {
        Calendar c = Calendar.getInstance();
        c.set(2022, 11,22);

        System.out.println(c.get(Calendar.MONDAY)+ "/" +c.get(Calendar.DATE));
        }
    }

 

형식화 클래스

날짜, 텍스트 데이터를 일정한 형식에 맞게 출력하기 위해 제공하는 클래스

 

1. DecimalFormat

숫자 데이터를 정수, 부동소수점, 금액 등의 다양한 형식을 표현 가능하며 반대의 경우도 가능하다

DecimalFormat 패턴에 사용되는 기호

public class Main {
    public static void main(String[] args) throws IOException {
        double num = 1234567.89;
        DecimalFormat df = new DecimalFormat("#.#E0");
        String result = df.format(num);
        System.out.println(result);
        }
    }

실행결과:

 

2. SimpleDataFormat

Date와 Calendar를 통해 계산한 날짜를 원하는(다양한)형태로 출력하는데 유용한 클래스

SimpleDataFormat에 사용되는 기호

public class Main {
    public static void main(String[] args) throws IOException {
        Calendar c = Calendar.getInstance();
        c.set(2022, 11,22);
        Date day = c.getTime();	// Calendar를 Date로 변환

        SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
        String result = df.format(day);
        System.out.println(result);
        }
    }

* Date 인스턴스만 format 메서드에 사용될 수 있기 때문에 getTime()메서드를 사용하여 Calendar인스턴스를 Date인스턴스로 변환해야한다

 

public class Main {
    public static void main(String[] args) throws IOException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat df2 = new SimpleDateFormat("yyyy/MM/dd");

        try{
            Date d = df.parse("2021-07-19");
            System.out.println(df2.format(d));
        } catch (Exception e){}

        }
    }

* parse를 사용하여 날짜 데이터의 출력형식을 변환하는 방법도 있다.

 

실행결과:

 

3. ChoiceFormat

특정 범위에 속하는 값을 문자열로 반환해준다.

import java.text.*;

public class Main {
    public static void main(String[] args) throws IOException {
        double[] limits = {60, 70, 80, 90};	// 낮은 값부터 큰 순으로
        String[] grades = {"D","C","B","A"};	// limits와 순서, 개수를 맞춰야함 

        int[] scores = {100, 95, 88, 70, 52, 60, 70};
        ChoiceFormat form = new ChoiceFormat(limits, grades);

        for(int i=0;i< scores.length;i++){
            System.out.println(scores[i]+":"+form.format(scores[i]));
        }

    }
}

실행 결과

 

4. MessageFormat

데이터를 정해진 양식에 맞게출력할 수 있도록 도와준다

import java.text.*;

public class Main {
    public static void main(String[] args) throws IOException {
        String msg = "Name: {0} \nTel: {1} \nAge:{2} \nBirth:{3}";

        Object[] arg = {"KimJenny", "02-123-4567", "27", "07-19"};
        String result = MessageFormat.format(msg, arg);
        System.out.println(result);

    }
}

실행 결과

728x90