728x90
반응형
날짜, 시간
날짜 시간 클래스
Date date = new Date();
현재 시스템의 날짜와 시간을 출력한다.
Date date = new Date();
System.out.println("오늘 날짜 : " + date);
// [실행결과] 오늘 날짜 : Wed Jul 17 15:00:21 KST 2024
날짜 시간, 형태 클래스
SimpleDateFormat();
날짜와 시간을 원하는 형태로 변경하여 출력한다.
SimpleDateFormat sdf = new SimpleDateFormat("y년 MM월 dd일 H시 m분 s초");
System.out.println("오늘 날짜 : " + sdf.format(date));
System.out.println();
// [실행결과] 오늘 날짜 : 2024년 07월 17일 15시 0분 21초
시간과 날짜 추상 클래스
Calendar cal = Calendar.getInstance();
Calendar 클래스의 static 상수값을 이용해 원하는 날짜, 시간 정보를 get() 메소드로 가져온다.
Calendar cal = Calendar.getInstance(); // 메소드 이용
int year = cal.get(Calendar.YEAR); //상수 static이다. final = 값을 고정하고 있다.
System.out.println(year);
// [실행결과] 2024
[예시]
오늘의 날짜 시간 출력하기
Calendar 클래스의 MONTH static상수는 1월이 0으로 출력되기 때문에 +1을 해야된다.
int month = cal.get(Calendar.MONTH)+1;
WEEK_OF_MONTH는 일요일부터 토요일까지 1부터 7로 부여된다.
int week = cal.get(Calendar.WEEK_OF_MONTH);
전체코드
Calendar cal = Calendar.getInstance(); // 메소드 이용
int year = cal.get(Calendar.YEAR); //상수 static이다. final = 값을 고정하고 있다.
int month = cal.get(Calendar.MONTH)+1; // 1월 = 0, 2월-1, 3월-2
int day = cal.get(Calendar.DATE);
int week = cal.get(Calendar.WEEK_OF_MONTH);
String weekOfDay = null;
switch (week){
case 1 : weekOfDay = "일" ; break;
case 2 : weekOfDay = "월" ; break;
case 3 : weekOfDay = "화" ; break;
case 4 : weekOfDay = "수" ; break;
case 5 : weekOfDay = "목" ; break;
case 6 : weekOfDay = "금" ; break;
case 7 : weekOfDay = "토" ; break;
}
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
System.out.println(year+" "+month+" "+day +" "+ weekOfDay + "요일 " + hour + ":" + minute+":"+second);
// [실행결과] 2024 7 17 화요일 15:0:21
728x90
반응형
'Java' 카테고리의 다른 글
Java, Package(패키지) / 다른 패키지에서 호출하기 (+접근제어자) / Object(최상위 클래스) 비교하기( == , equals()) (1) | 2024.07.18 |
---|---|
Java, Final(상수화) 란? / instanceof / 색(RGB) (0) | 2024.07.18 |
Java, 추상 클래스 NumberFormat 이용하기 / DecimalFormat / getCurrencyInstance( 나라별로 숫자(돈) 표현 ) (0) | 2024.07.17 |
Java, 생성자 메소드/ this와 this()의 차이 / varargs (0) | 2024.07.17 |
Java, 추상 클래스(abstract method) (0) | 2024.07.16 |