API - 날짜 관련(Calendar...)

JK·2022년 12월 27일
0

JAVA

목록 보기
21/28
post-thumbnail

날짜(Calendar와 GregorianCalendar)

  • 날짜와 시간을 표현할 때 많이 쓰이는 Calendar클래스는 싱글톤클래스
  • 날짜와 시간을 표현할 때 많이 쓰이는 GregorianCalendar클래스는 일반클래스

같은 출력값을 Calender와 GregorianCalendar를 사용해보기

1. Calender

code

public class Ex01_Calender {
	public static void main(String[] args) {
		Calendar now =Calendar.getInstance();
//		System.out.println(now);
		// 2022년 12월 14일 수요일 09시48분
		int year = now.get(Calendar.YEAR);     //YEAR = static field   get에 1을 넣으면 알아서 year로 반환
		int month = now.get(Calendar.MONTH) + 1;   //MONTH = static final    시스템 상 0월부터 시작하기에 +1
		int day = now.get(Calendar.DAY_OF_MONTH);  
		int week = now.get(Calendar.DAY_OF_WEEK);  //1:일 2:월 3:화 ... 7:토
		int hour24 = now.get(Calendar.HOUR_OF_DAY);  // 24시간 
		int hour = now.get(Calendar.HOUR);   // 12시간  (오전, 오후 나눠줘야함)
		int ampm = now.get(Calendar.AM_PM);  //0:오전  1:오후
		int minute = now.get(Calendar.MINUTE);
		int second = now.get(Calendar.SECOND);
		int milliSec = now.get(Calendar.MILLISECOND);
		System.out.printf("%d년 %d월 %d일", year, month, day);
		switch(week) {
		case 1: System.out.print("일요일"); break;
		case 2: System.out.print("월요일"); break;
		case 3: System.out.print("화요일"); break;
		case 4: System.out.print("수요일"); break;
		case 5: System.out.print("목요일"); break;
		case 6: System.out.print("금요일"); break;
		case 7: System.out.print("토요일"); break;
		}
		System.out.printf("\t%d시 %d분 %d초" + ("  %s %d시 %d분 %d초\n"), hour24, minute, second,
						(ampm == 0 ? "오전" : "오후"), hour, minute, second);
		//%d(정수)
		// %td(년) %tm(월) %td(일) %ta(요일) %tp(오전/오후) %tl(12시간) %tM(분) %tS(초)
		System.out.printf("%1$td년 %1$tm월 %1$td일 %1$ta요일 %1$tH시 %1$tM분 %1$tS초(%1$tp %1$tl시)\n", now);
	}
}

결과

2022년 12월 24일토요일	21시 46분 4초  오후 9시 46분 4초
24년 12월 24일 토요일 21시 46분 04초(오후 9시)

2. GregorianCalendar

code

public class Ex02_GregorianCalender {
	public static void main(String[] args) {
		GregorianCalendar now = new GregorianCalendar();
//		Calendar now =Calendar.getInstance();
//		System.out.println(now);
		// 2022년 12월 14일 수요일 09시48분
		int year = now.get(Calendar.YEAR);     //YEAR = static field   get에 1을 넣으면 알아서 year로 반환
		int month = now.get(Calendar.MONTH) + 1;   //MONTH = static final    시스템 상 0월부터 시작하기에 +1
		int day = now.get(Calendar.DAY_OF_MONTH);  
		int week = now.get(Calendar.DAY_OF_WEEK);  //1:일 2:월 3:화 ... 7:토
		int hour24 = now.get(Calendar.HOUR_OF_DAY);  // 24시간 
		int hour = now.get(Calendar.HOUR);   // 12시간  (오전, 오후 나눠줘야함)
		int ampm = now.get(Calendar.AM_PM);  //0:오전  1:오후
		int minute = now.get(Calendar.MINUTE);
		int second = now.get(Calendar.SECOND);
		int milliSec = now.get(Calendar.MILLISECOND);
		System.out.printf("%d년 %d월 %d일", year, month, day);
		switch(week) {
		case 1: System.out.print("일요일"); break;
		case 2: System.out.print("월요일"); break;
		case 3: System.out.print("화요일"); break;
		case 4: System.out.print("수요일"); break;
		case 5: System.out.print("목요일"); break;
		case 6: System.out.print("금요일"); break;
		case 7: System.out.print("토요일"); break;
		}
		System.out.printf("\t%d시 %d분 %d초" + ("  %s %d시 %d분 %d초\n"), hour24, minute, second,
						(ampm == 0 ? "오전" : "오후"), hour, minute, second);
		//%d(정수)
		// %td(년) %tm(월) %td(일) %ta(요일) %tp(오전/오후) %tl(12시간) %tM(분) %tS(초)
		System.out.printf("%1$td년 %1$tm월 %1$td일 %1$ta요일 %1$tH시 %1$tM분 %1$tS초(%1$tp %1$tl시)\n", now);
	}
}

결과

2022년 12월 24일토요일	21시 46분 40초  오후 9시 46분 40초
24년 12월 24일 토요일 21시 46분 40초(오후 9시)

turm(두 시점 계산)

(now - checkOut) 계산이 안 되어 -> 1970년 1월 1일 부터 now 까지의 밀리세컨 - 1970년 1월 1일 부터 check 까지의 밀리세컨으로 계산

package com.lec.ex2_date;

import java.util.Date;
import java.util.GregorianCalendar;

public class Ex03_term {
	public static void main(String[] args) {
		Date now = new Date();  //지금
		//대출시점 
        Date checkOut = new Date(new GregorianCalendar(2022, 10, 28).getTimeInMillis());  
  
		long nowMillis = now.getTime();    // 1970.1.1 ~ now까지의 밀리세컨
		long checkMillis = checkOut.getTime(); //1970. 1. 1 ~ checkOut 까지의 밀리세컨
		
//		GregorianCalendar now = new GregorianCalendar();  // 현재
//		long nowMillis =now.getTimeInMillis();   
//		now.getTimeInMillis()는 1970년 1월 1일 부터 now 까지의 밀리세컨
//		GregorianCalendar checkOut = new GregorianCalendar(2022, 10, 28, 9, 30);  // 대출시점
//		long checkMillis = checkOut.getTimeInMillis(); //checkOut.getTimeInMillis(); 는   
//		1970년 1월 1일 부터 checkOut 까지의 밀리세컨
		
		int day = (int)((nowMillis - checkMillis)/(1000*60*60*24));    
        //(1000*60*60*24)  밀리세컨->초->분->일   
//		//nowMillis, checkMillis 는 8byte 이기에 int로 형변환
		System.out.println("몇일 지났나 : " + day);
	}
}

Date

  • Date는 잘 쓰이지 않는다
package com.lec.ex2_date;

import java.util.Date;

public class Ex04_date {
	public static void main(String[] args) {
		Date now = new Date();
		System.out.println(now);
		int year = now.getYear() + 1900; 
		int month = now.getMonth() + 1; 
		int day = now.getDate();          //잘 안 쓰이는 것들
		System.out.println(year + "년" + month + "월" + day + "일");
		System.out.printf("%1$td년 %1$tm월 %1$td일 %1$ta요일 %1$tH시 %1$tM분 %1$tS초(%1$tp %1$tl시)\n", now);
	}
}

SimpleDateFormat

  • SimpleDateFormat은 날짜의 형식을 정하는 API
  • 하나의 데이터를 여러가지 형식으로 출력해보았다
package com.lec.ex2_date;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

public class Ex07_SimpleDateFormat {
	public static void main(String[] args) {
//		Date date = new Date(2022-1900, 10, 28, 9, 30);  //2022.11.28 9:30
		Date date = new Date(new GregorianCalendar(2022, 10, 28, 9, 30).getTimeInMillis());  //Date() 괄호 안에 long형을 넣음
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy, MM, dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yy년 MM월 dd일 HH:mm:ss");
		SimpleDateFormat sdf3 = new SimpleDateFormat("yy-MM-dd(E) a H:mm:ss");
		SimpleDateFormat sdf4 = new SimpleDateFormat("오늘은 올해의 D번째 날입니다");
		SimpleDateFormat sdf5 = new SimpleDateFormat("이번주는 올해의 w번째 주입니다");
		System.out.println(sdf1.format(date));
		System.out.println(sdf2.format(date));
		System.out.println(sdf3.format(date));
		System.out.println(sdf4.format(date));
		System.out.println(sdf5.format(date));
	}
}

결과

2022, 11, 28
22년 11월 28일 09:30:00
22-11-28(월) 오전 9:30:00
오늘은 올해의 332번째 날입니다
이번주는 올해의 49번째 주입니다

EX

ex1. 오늘 생일인 친구 검색하기

  • today는 12-24
  • month : now.get(Calendar.MONTH) + 1; 을 이용
    시스템 상 month는 0부터 시작하기에 +1을 해주었다
  • String monthStr = month<10 ? "0"+month : ""+month;
    빈 스트링을 더해서 month를 int에서 string 으로 형변환
package com.lec.ex2_date;

import java.util.Calendar;
import java.util.GregorianCalendar;
import com.lec.ex4_object.Friend;

//오늘 생일인 친구들 출력
public class Ex05_FriendBirth {
	public static void main(String[] args) {
		Friend[] friends = { new Friend("홍길동", "010-9999-9999", "12-14", "서울 서대문"),
							 new Friend("김길동", "010-9999-3333", "12-26", "수원 영통"),
							 new Friend("김수환", "010-9999-1111", "02-17", "서울 용산"),
							 new Friend("거북이", "010-6666-6666", "03-03", "인천 송도")};
		GregorianCalendar now = new GregorianCalendar();
		int month = now.get(Calendar.MONTH) + 1;  // 시스템상 월이 0부터 시작하기에 +1을 해준다
		int day = now.get(Calendar.DAY_OF_MONTH);
		String monthStr = month<10 ? "0"+month : ""+month;   
        //빈 스트링을 더해서 month를 int에서 string 으로 형변환
		String dayStr = day<10 ? "0"+day : ""+day;
		String today = monthStr + "-" + dayStr;
		System.out.println(today);
		boolean none = true;
		System.out.println("오늘 생일인 친구 목록을 검색합니다");
		for(int idx=0 ; idx<friends.length ; idx++) {
			String birth = friends[idx].getBirth();
			if(today.equals(birth)) {
				System.out.println(friends[idx]);
				none = false;         //한명 이상 출력 시 none = false
			}//if
		}//for
		if(none) {
			System.out.println("오늘 생일인 친구가 없습니다");
		}
	}//main
}//class

결과

12-24
오늘 생일인 친구 목록을 검색합니다
[이름]거북이[전화번호]010-6666-6666[생일]12-24[주소]인천 송도

ex2. SimpleDateFormat을 활용한 오늘 생일인 친구 검색하기

  • today는 12-24
package com.lec.ex2_date;

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;

import com.lec.ex4_object.Friend;

//오늘 생일인 친구들 출력
public class Ex08_FriendBirth {
	public static void main(String[] args) {
		Friend[] friends = { new Friend("홍길동", "010-9999-9999", "12-14", "서울 서대문"),
							 new Friend("김길동", "010-9999-3333", "12-14", "수원 영통"),
							 new Friend("김수환", "010-9999-1111", "02-17", "서울 용산"),
							 new Friend("거북이", "010-6666-6666", "12-24", "인천 송도")};
		GregorianCalendar now = new GregorianCalendar();
		SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd");
		String today = sdf1.format(now.getTime());
		boolean none = true;
		System.out.println("오늘 생일인 친구 목록을 검색합니다");
		for(Friend friend : friends) {
			if(today.equals(friend.getBirth())) {
				System.out.println(friend);
				none = false;
			}
		}//for
		if(none) {
			System.out.println("오늘 생일인 친구가 없습니다");
		}
	}//main
}//class

결과

오늘 생일인 친구 목록을 검색합니다
[이름]거북이[전화번호]010-6666-6666[생일]12-24[주소]인천 송도

ex3. 사원의 사번, 이름, 부서, 입사일 출력

1. Sawon

  • final 변수로 부서 이름 입력
  • 사번 이름 부서 입사일 데이터 입력
  • 입사일이 기존에 있던 생성자, 입사일이 당일인 생성자 생성
  • toString을 이용하여 출력값 틀 정하기
package com.lec.ex2_date;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

public class QuizSawon {
	public static final String COMPUTER = "COMPUTER";
	public static final String PLANNING = "PLANNING";
	public static final String DESIGN = "DESIGN";
	public static final String ACCOUNTING = "ACCOUNTING";
	public static final String HUMANRESOURCES = "HUMANRESOURCES";
	private String sawonNo;
	private String name;
	private String depart;
	private Date hireday;

	public QuizSawon(String sawonNo, String name, String depart) {
		this.sawonNo = sawonNo;
		this.name = name;
		this.depart = depart;
		hireday = new Date();
	}

	public QuizSawon(String sawonNo, String name, String depart, int y, int M, int d) {
		this.sawonNo = sawonNo;
		this.name = name;
		this.depart = depart;
		hireday = new Date(new GregorianCalendar(y, M - 1, d).getTimeInMillis());
	}

	@Override
	public String toString() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy, MM, dd");
		return "[사번]" + sawonNo + "\t[이름]" + name + "\t[부서]" + depart + "\t[입사일]" + sdf.format(hireday);
	}
}

2. Main

  • 일반 for문, 확장 for문을 다 사용하여 두 번 출력해보았다
package com.lec.ex2_date;

public class QuizSawonMain {

	public static void main(String[] args) {
		QuizSawon[] sawons = { new QuizSawon("a01", "홍길동", QuizSawon.COMPUTER),
						   new QuizSawon("a02", "박길동", QuizSawon.DESIGN, 2022, 7, 12),
						   new QuizSawon("b01", "이길동", QuizSawon.PLANNING, 2022, 10, 15)};
		for(int i=0 ; i<sawons.length ; i++) {
			System.out.println(sawons[i]);
		}
		System.out.println();
		for(QuizSawon sa : sawons) {
			System.out.println(sa);
		}
	}
}

결과

[사번]a01	[이름]홍길동	[부서]COMPUTER	[입사일]2022, 12, 24
[사번]a02	[이름]박길동	[부서]DESIGN	[입사일]2022, 07, 12
[사번]b01	[이름]이길동	[부서]PLANNING	[입사일]2022, 10, 15

[사번]a01	[이름]홍길동	[부서]COMPUTER	[입사일]2022, 12, 24
[사번]a02	[이름]박길동	[부서]DESIGN	[입사일]2022, 07, 12
[사번]b01	[이름]이길동	[부서]PLANNING	[입사일]2022, 10, 15
profile
씨앗 개발자

0개의 댓글