Java/Java
[Java(자바)] 현재 날짜, 현재 시간 구하기
너무 궁금해
2025. 3. 4. 11:52
[Java(자바)] 현재 날짜, 현재 시간 구하기
✅ LocalDate 사용 (날짜만 필요할 때)
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("현재 날짜: " + today);
// 포맷 적용하기
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String nowString = now.format(formatter);
System.out.println("포맷팅 날짜: " + nowString);
}
}
👉 출력 결과
현재 날짜: 2025-03-04
포맷팅 날짜: 2025/03/04
✅ LocalDateTime 사용 (날짜와 시간 필요할 때)
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("현재 날짜와 시간: " + now);
}
}
👉 출력 결과
현재 날짜와 시간: 2025-03-04T14:30:45.123
✅ ZonedDateTime 사용 (시간대 포함)
import java.time.ZonedDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
ZonedDateTime seoulTime = ZonedDateTime.now(ZoneId.of("Asia/Seoul"));
System.out.println("서울 시간: " + seoulTime);
}
}
👉 출력 결과
서울 시간: 2025-03-04T14:30:45.123+09:00[Asia/Seoul]
✅ Date 클래스 사용 (구버전(버전 8 이전), 권장X)
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
System.out.println("현재 날짜와 시간: " + date);
}
}
👉 출력 결과
현재 날짜와 시간: Tue Mar 04 14:30:45 KST 2025