Java에서 현재 날짜를 가져오는 방법은 Java 8부터 추가된 java.time 패키지의 LocalDate 클래스를 사용하는 것입니다. 아래는 해당 방법입니다.
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
System.out.println("현재 날짜: " + currentDate);
}
}
위 코드를 실행하면 "YYYY-MM-DD" 형식으로 현재 날짜가 출력됩니다. 예를 들면 "2023-06-09"와 같습니다.
때로는 LocalDate 객체를 원하는 형식으로 변환해야 할 때가 있습니다. 이를 위해 java.time.format.DateTimeFormatter 클래스를 사용합니다. 아래는 LocalDate 객체를 원하는 형식으로 변환하는 예제입니다.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
String formattedDate = currentDate.format(formatter);
System.out.println("형식 변환된 날짜: " + formattedDate);
}
}
위 코드에서는 날짜를 "yyyy/MM/dd HH:mm" 형식으로 변환하고 출력합니다. 포맷 문자열을 변경하여 원하는 형식으로 날짜를 변환할 수 있습니다. 예를 들면 "2023/06/09 15:30"과 같습니다.
이와 같이 Java의 java.time 패키지를 사용하면 현재 날짜를 가져오고 원하는 형식으로 변환할 수 있습니다.