1. 📌 Date 클래스 — 기본적인 날짜 객체
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
Date now = new Date();
System.out.println("현재 시간: " + now);
}
}
📖 Date 클래스는 Java에서 오래전부터 사용되던 날짜 클래스입니다.
하지만 setYear(), getMonth() 등의 메서드는 현재 deprecated 되었기 때문에 읽기 전용으로 사용되는 경우가 많습니다.
2. 📌 Calendar & GregorianCalendar — 날짜 조작에 유용
import java.util.Calendar;
import java.util.GregorianCalendar;
public class CalendarExample {
public static void main(String[] args) {
Calendar calendar = new GregorianCalendar(2025, Calendar.APRIL, 29);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 0부터 시작하므로 +1
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.printf("설정된 날짜는 %d년 %d월 %d일입니다.%n", year, month, day);
}
}
🔍 Calendar는 날짜 계산이 필요한 경우 많이 사용됩니다. 예를 들어 특정 날짜에 며칠을 더하거나 비교 연산을 수행할 수 있습니다.
3. 📌 SimpleDateFormat — 날짜를 원하는 형식으로 포맷
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(now);
System.out.println("형식화된 현재 시간: " + formattedDate);
}
}
🎨 SimpleDateFormat은 날짜를 문자열로 표현하거나, 문자열을 날짜로 파싱할 때 매우 유용합니다.
📌 주요 포맷 기호 예시:
기호의미예시
yyyy | 연도 | 2025 |
MM | 월 (2자리) | 04 |
dd | 일 (2자리) | 29 |
HH | 시 (24시간제) | 14 |
mm | 분 | 35 |
ss | 초 | 07 |
🧠 마무리
Java에서는 Date를 시작으로, Calendar, GregorianCalendar, 그리고 SimpleDateFormat까지 다양한 클래스를 통해 날짜와 시간을 다룰 수 있습니다. 자바 8 이후에는 LocalDate, LocalDateTime, DateTimeFormatter 등 새로운 API가 등장했지만, 기존 코드나 레거시 시스템에서는 여전히 위 클래스들이 자주 사용됩니다.
'JAVA API' 카테고리의 다른 글
🔍 [Java 기초] 자바에서 문자열 다루기: append(), insert(), delete(), concat(), reverse() 메서드 ✨ (1) | 2025.04.28 |
---|---|
🔍 [Java 기초] 기본형 Wrapper 클래스의 toString() 메서드 완벽 정리 (1) | 2025.04.24 |