자바 날짜 및 시간
자바 날짜
Java에는 내장된 Date 클래스가 없지만 java.time
날짜 및 시간 API와 함께 작동하도록 패키지를 가져올 수 있습니다. 패키지에는 많은 날짜 및 시간 클래스가 포함되어 있습니다. 예를 들어:
Class | Description |
---|---|
LocalDate |
Represents a date (year, month, day (yyyy-MM-dd)) |
LocalTime |
Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns)) |
LocalDateTime |
Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns) |
DateTimeFormatter |
Formatter for displaying and parsing date-time objects |
패키지가 무엇인지 모르는 경우 Java 패키지 자습서 를 읽으십시오 .
현재 날짜 표시
현재 날짜를 표시하려면 java.time.LocalDate
클래스를 가져오고 해당 now()
메서드를 사용합니다.
예시
import java.time.LocalDate; // import the LocalDate class
public class Main {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // Create a date object
System.out.println(myObj); // Display the current date
}
}
출력은 다음과 같습니다.
2022-01-29
현재 시간 표시
현재 시간(시, 분, 초 및 나노초)을 표시하려면 java.time.LocalTime
클래스를 가져오고 해당 now()
메서드를 사용합니다.
예시
import java.time.LocalTime; // import the LocalTime class
public class Main {
public static void main(String[] args) {
LocalTime myObj = LocalTime.now();
System.out.println(myObj);
}
}
출력은 다음과 같습니다.
11:44:31.892946
현재 날짜 및 시간 표시
현재 날짜와 시간을 표시하려면 java.time.LocalDateTime
클래스를 가져오고 해당 now()
메서드를 사용합니다.
예시
import java.time.LocalDateTime; // import the LocalDateTime class
public class Main {
public static void main(String[] args) {
LocalDateTime myObj = LocalDateTime.now();
System.out.println(myObj);
}
}
출력은 다음과 같습니다.
2022-01-29T11:44:31.892089
날짜 및 시간 형식 지정
위의 예에서 "T"는 날짜와 시간을 구분하는 데 사용됩니다. DateTimeFormatter
동일한 패키지 의 메서드와 함께 클래스를 사용하여 ofPattern()
날짜-시간 개체의 형식을 지정하거나 구문 분석할 수 있습니다. 다음 예는 날짜-시간에서 "T"와 나노초를 모두 제거합니다.
예시
import java.time.LocalDateTime; // Import the LocalDateTime class
import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class
public class Main {
public static void main(String[] args) {
LocalDateTime myDateObj = LocalDateTime.now();
System.out.println("Before formatting: " + myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDate = myDateObj.format(myFormatObj);
System.out.println("After formatting: " + formattedDate);
}
}
출력은 다음과 같습니다.
Before Formatting: 2022-01-29T11:44:31.892134
After Formatting: 29-01-2022 11:44:31
ofPattern()
다른 형식으로 날짜와 시간을 표시하려는 경우 이 메서드는 모든 종류의 값을 허용합니다. 예를 들어:
Value | Example | Tryit |
---|---|---|
yyyy-MM-dd | "1988-09-29" | |
dd/MM/yyyy | "29/09/1988" | |
dd-MMM-yyyy | "29-Sep-1988" | |
E, MMM dd yyyy | "Thu, Sep 29 1988" |