현재 날짜 및 시간을 가져오고 다양한 형식으로 출력하는 것을 알아봅니다. 이 글에서는 LocalDateTime와 DateTimeFormatter을 사용하여 날짜 및 시간을 출력합니다.
현재 날짜/시간 가져오기, 기본형식으로 출력
LocalDateTime.now()
는 현재 날짜와 시간을 가져옵니다.
LocalDate.now
는 현재 날짜만 가져옵니다.
import java.time.LocalDate
import java.time.LocalDateTime
fun main(args: Array<String>) {
val dateAndtime: LocalDateTime = LocalDateTime.now()
val onlyDate: LocalDate = LocalDate.now()
println("Current date and time: $dateAndtime")
println("Current date: $onlyDate")
}
출력하면 다음과 같은 형식으로 출력됩니다.
Current date and time: 2019-03-23T00:05:54.608
Current date: 2019-03-23
참고로, 특정 시간의 LocalData, LocalDateTime을 생성하려면 of()
를 사용하면 됩니다.
LocalDate.of(2019, 3, 22) // 2019년 3월 22일
LocalDateTime.of(2019, 3, 22, 10, 10, 10) // 2019년 3월 22일 10시 10분 10초
이미 정의된 형식으로 출력
DateTimeFormatter
을 사용하면 다른 형식으로 출력할 수 있습니다.
ISO_DATE
는 라이브러리에서 제공하는, 이미 정의된 형식입니다. 이외에 다양한 것들이 있습니다.
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ISO_DATE
val formatted = current.format(formatter)
println("Current: $formatted")
}
출력
Current: 2019-03-22
라이브러리에서 제공하는 DateTimeFormatter의 포맷들은 다음과 같은 것들이 있습니다.
상수 | 출력 예제 |
---|---|
ISO_DATE_TIME | 2019-03-22T23:56:36.4 |
ISO_LOCAL_DATE | 2019-03-22 |
ISO_LOCAL_TIME | 23:56:36.4 |
ISO_LOCAL_DATE_TIME | 2019-03-22T23:56:36.4 |
ISO_DATE | 2019-03-22 |
ISO_TIME | 23:56:36.4 |
다른 형식으로 출력
DateTimeFormatter.ofPattern()
를 사용하면 원하는 형식으로 출력할 수 있습니다. 대신 패턴을 만들어 인자로 전달해줘야 합니다.
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy년 MM월 dd일 HH시 mm분 ss초")
val formatted = current.format(formatter)
println("Current: $formatted")
}
출력
Current: 2019년 03월 22일 23시 46분 36초
DateTimeFormatter.ofPattern()
에서 다음과 같은 패턴들을 사용할 수 있습니다.
패턴 | 예제 |
---|---|
yyyy-MM-dd | “2019-07-04” |
dd-MMM-yyyy | “04-July-2019” |
dd/MM/yyyy | “04/07/2019” |
yyyy-MM-dd'T'HH:mm:ssZ | “2019-07-04T12:30:30+0530” |
h:mm a | “12:00 PM” |
yyyy년 MM월 dd일 | "2019년 01월 10일" |
정리
LocalDateTime, LocalDate을 생성하고 다양한 방식으로 출력하는 것을 알아보았습니다.