본문 바로가기
BackEnd/Java

Date와 Calendar

by pplucy 2020. 10. 29.

1. Date

  1)  Date클래스는 자바개발 초기에 급하게 만들어져 완성도가 낮고 특히 다국적으로 쓰이기에는 한계가 있다.

  2)  Date클래스에서 '년도'에는 1900을, '월'에는 1을 더해줘야 한다. 

 

 

2. Calendar

 1) TimeZone 기능제공

    - TimeZone : 특정 국가나 지역의 현지시간

    - GMT(그리니치 표준시, 경도 0도 태양이 지나가는 시간)를 시준으로 지역의 시간이 몇 시간이나 빠른지 혹은 느린지로 표시한다.

       한국은 GMT보다 9시간 빠름

       TimeZone을 표시할 때에는 ST DST로 나눠서 표기한다.

     - ST : 표준적인 시간 계산

     - DST(Daylight Savinr Time) : 일광 절약 시간제(썸머타임) , 하절기에 시간을 1시간 빠르게 계산

     - TimeZone 표기를 할 경우 ST를 따르면 가운데에 S, DST를 따르면 가운데에 D표시

        ex) KST, JST, EST, KDT, JDT, EDT

 

 2) field number 개념도입

    - Calendar 클래스에서 제공해주는 메서드들의 매개변수로 활용되며 특정한 의미를 지니는 상수

      -> API에서 확인가능하다.

 

 3) Calendar는 '추상클래스'

    - Calendar calendar = new Calendar 의 형태로 인스턴스화가 불가능하다.

    - Calendar calendar = Calendar.getInstance(); 를 이용하면 현재시간 반환가능! API에서 사용권장

    - GregorianCalendar를 반환해준다.     

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.kh.a_date;
 
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
 
public class DateTest {
    
    public void date() {
    // 1. Date
 
    //java.util.Date
    Date today = new Date();
    System.out.println(today);
 
    
    
    //년 월 일 시 분 초
    System.out.println("년: " +( today.getYear() + 1900));  
    System.out.println("월: " +( today.getMonth() + 1));
    System.out.println("일: " + today.getDate());
    System.out.println("시: " + today.getHours());
    System.out.println("분: " + today.getMinutes());
    System.out.println("초: " + today.getSeconds());
    
 
    
    }
    
    
    public void calendarTest() {
        
        // 2. Calendar
    
        
        //현재 날짜를 알 수 있다.
        Calendar calendar = Calendar.getInstance();
        //getInstance의 내부 형태 Calendar calendar2 = new GregorianCalendar();
        //return calendar2;
        System.out.println("GragorianCalendar의 인스턴스 입니까? "
                            + (calendar instanceof GregorianCalendar));
        
        //getTime : Calendar 인스턴스의 시간을 가지는 Date인스턴스를 반환
        Date date = calendar.getTime(); //getTime안에 리턴값이 return new Date(getTimeInMillis());이기 떄문에
                                        //new 연산자를 쓰지 않아도 가능한 것. 또한 date인스턴스에는 long타입 생성자가 존재해 date(long)형태로
                                        //입력값이 들어오게 되면 그게 설정되어있는 포맷으로 반환되어 나타난다
        System.out.println(date);
        
        
        // set메서드를 통해 원하는 시간으로 지정
        // month원하는 달보다 1작은 값을 넣어야 한다.
        calendar.set(2020922115959);    
        System.out.println(date);
        
        
        // 년월일시분초 출력하기
        System.out.println("년: " + calendar.get(calendar.YEAR));
        System.out.println("월: " + (calendar.get(calendar.MONTH)+1));
        System.out.println("일: " + calendar.get(calendar.DATE));
        System.out.println("시: " + calendar.get(calendar.HOUR));
        System.out.println("분: " + calendar.get(calendar.MINUTE));
        System.out.println("초: " + calendar.get(calendar.SECOND));
        
        
        
        // setTime() : 매개변수로 넘어온 Date의 시간을 Calendar에 세팅
        Date today = new Date(); //오늘 날짜로 Date 인스턴스 생성
        calendar.setTime(today); //오늘 날짜로 변경
        System.out.println();
        System.out.println(calendar.getTime());
        
        // getTimeInMillis()
        // Epoch(1970/01/01 00:00:00 GMT)로부터 calendar에 담긴 시간 사이의
        // 시간을 millisecond(1/1000초)로 반환
        System.out.println(calendar.getTimeInMillis());
        System.out.println("1970년 1월 1일 이후" + (calendar.getTimeInMillis()/1000 + "초가 흘렀습니다."));
        
 
        
        
    }
    
    
    
 
    }
 
 
cs

 

 

 

* 이 개념을 공부하면서 헷갈렸던 부분

 

Date date = calendar.getTime();

 

이 개념이다 왜 new연산자 없이 calendar.getTime이 올 수 있는지 궁금했고 굳이 왜 calendar.getTime을 date 인스턴스로 출력하려고 하는지 궁금했다. 그 이유는,

 

1) 저 getTime 안에 리턴값이 return new Date(getTimeInMillis());이기 때문에!

    => new연산자가 리턴값에 만들어져 있다.

2) Date 클래스 생성자의 타입이 long인 생성자가 있기 때문에

    => 기본적으로 getTimeMillis로 시간을 출력하면 리턴값이 long 타입이기 때문에

          이걸 date클래스가 생성자로 받아 정해진 포맷대로 변환해서 출력하는 것 !

 

 


  Calendar클래스의 메소드

  - getTime() : calendar 인스턴스에 세팅된 시간값을 가지는 Date인스턴스 변환

 

  SimpleDateFormat 클래스의 메소드

  - format(Date date) : SimpleDateFormat에 등록된 format대로 시간을 문자열로 반환해주는 메서드                                       

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class DateFormatter {
 
    
    public void formatterTest() {
        
 
        
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getTime());
        
        //calendar의 시간을 먼저 변경해준다. -> 원하는 시간으로
        //SimpleDateFormat의 생성자 매개변수에 원하는 포맥을 작성해서 전달.
        calendar.set(20209251211);
        SimpleDateFormat sdf = new SimpleDateFormat("\n 오늘은 yyyy-MM-dd E요일 hh시 mm분 ss초");
        
        
        //getTime() : calendar 인스턴스에 세팅된 시간값을 가지는 Date인스턴스 변환
        //format(Date date) : SimpleDateFormat에 등록된 format 대로 시간을 문자열로 반환해주는 메서드
        //                    -> 내가 날짜를 설정해도 그 값을 반환해줌
        System.out.println(sdf.format(calendar.getTime()));
        
        
        
        
    }
    
    
}
cs

 

'BackEnd > Java' 카테고리의 다른 글

IO_BufferedInputStream & BufferedOutputStream  (0) 2020.10.31
IO_FileOutPutStream & FileInputStream  (0) 2020.10.31
IO _ File 클래스  (0) 2020.10.31
IO (입출력)  (0) 2020.10.31
패키지와 변수  (0) 2020.09.23

댓글