- Java에는 날짜와 시간을 다루는 다양한 클래스 존재.
- Date, Calendar, LocalDateTime, SimpleDateFormat 등등
📢 Date 클래스
Date 클래스는 날짜와 시간을 표현하기 위해 사용되지만, deprecated 상태로 더 이상 권장되지 않음.
Date d = new Date();
System.out.println(d);
결과
Mon Oct 14 15:30:45 UTC 2024
📢 Calendar 클래스
Date의 후속작. 날짜와 시간을 더 편리하게 다룰 수 있음. Calendar 객체는 getInstance() 메서드를 사용하여 생성.
Calendar c = Calendar.getInstance();
현재 날짜와 시간 정보를 출력
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH) + 1; // 0~11 범위이므로 +1
int day = c.get(Calendar.DAY_OF_MONTH);
int week = c.get(Calendar.DAY_OF_WEEK);
날짜 출력
String weekStr = ""; // 요일 문자열 변환
switch (week) {
case 1: weekStr = "일"; break;
case 2: weekStr = "월"; break;
// ... (생략)
}
System.out.println(year + "-" + month + "-" + day + "(" + weekStr + ")");
결과
2024-10-14(월)
📢 LocalDateTime 클래스
- Java 8부터는 LocalDateTime 클래스를 사용하여 날짜와 시간을 다루는 것이 더 직관적이다.
- LocalDateTime은 java.time 패키지에 포함되어 있으며, 현재 날짜와 시간을 쉽게 알 수 있다.
LocalDateTime today = LocalDateTime.now();
System.out.println(today);
결과
2024-10-14T15:30:45.123456789
DateTimeFormatter - 포맷된 현재 날짜와 시간 출력
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
System.out.println(dtf.format(today));
결과
2024/10/14 15:30:45
📢 SimpleDateFormat 클래스
날짜 형식의 문자열을 원하는 포맷으로 변경
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd(E) hh:mm:ss");
String formattedDate = sdf.format(new Date());
System.out.println(formattedDate);
결과
2024-10-14(월) 03:30:45
문자열을 Date 객체로 변환
String dateStr = "2024-10-07(월) 04:48:00";
Date date = sdf.parse(dateStr);
System.out.println(date);
결과
Mon Oct 07 04:48:00 UTC 2024
시간은 코드의 흐름 속에 존재한다.
'백엔드 > Java' 카테고리의 다른 글
| Java 예외 처리 실습 (1) | 2024.10.20 |
|---|---|
| Java 예외 처리 (0) | 2024.10.17 |
| Java로 고객 관리 시스템 구현 (2) | 2024.10.15 |
| 객체지향 프로그래밍 (1) | 2024.10.14 |
| Java로 학생 정보 관리 시스템 구현(3) (0) | 2024.10.13 |