안드로이드 앱 개발 공부/자꾸 까먹어서 적어두는 구현방법

[Android] 코틀린Kotlin 현재 날짜 가져오기

플래시🦥 2023. 4. 3.
반응형

LocalDateTime 혹은 LocalDate

val localDateTime: LocalDateTime = LocalDateTime.now()
val localDate: LocalDate = LocalDate.now()
Log.d("localDateTime",localDateTime.toString())
Log.d("localDate",localDate.toString())

이렇게 하면 로그에 아래처럼 찍힌다. 

localDateTime  2023-04-03T 05:08:43.775
localDate  2023-04-03

 

 

LocalDateTime을 가지고 이렇게 시간과 날짜를 각각 가져올 수도 있다.

Log.d("localDateTime",localDateTime.toLocalDate().toString())
Log.d("localDateTime",localDateTime.toLocalTime().toString())

결과

localDateTime  2023-04-03
localDateTime  05:11:12.465

 

 

LocalDate.of(2022,3,14)
LocalDateTime.of(2023, 3, 1, 1, 15, 50)

이렇게 하면 특정 날짜를 지정할 수도 있다. 

 

특정 포맷 지정

https://developer.android.com/reference/java/time/format/DateTimeFormatter

 

DateTimeFormatter  |  Android Developers

 

developer.android.com

위 링크에 이동해서 보면 여러 포맷을 확인할 수 있다. 

 

Formatter Description Example
ofLocalizedDate(dateStyle) Formatter with date style from the locale '2011-12-03'
ofLocalizedTime(timeStyle) Formatter with time style from the locale '10:15:30'
ofLocalizedDateTime(dateTimeStyle) Formatter with a style for date and time from the locale '3 Jun 2008 11:05:30'
ofLocalizedDateTime(dateStyle,timeStyle) Formatter with date and time styles from the locale '3 Jun 2008 11:05'
BASIC_ISO_DATE Basic ISO date '20111203'
ISO_LOCAL_DATE ISO Local Date '2011-12-03'
ISO_OFFSET_DATE ISO Date with offset '2011-12-03+01:00'
ISO_DATE ISO Date with or without offset '2011-12-03+01:00'; '2011-12-03'
ISO_LOCAL_TIME Time without offset '10:15:30'
ISO_OFFSET_TIME Time with offset '10:15:30+01:00'
ISO_TIME Time with or without offset '10:15:30+01:00'; '10:15:30'
ISO_LOCAL_DATE_TIME ISO Local Date and Time '2011-12-03T10:15:30'
ISO_OFFSET_DATE_TIME Date Time with Offset '2011-12-03T10:15:30+01:00'
ISO_ZONED_DATE_TIME Zoned Date Time '2011-12-03T10:15:30+01:00[Europe/Paris]'
ISO_DATE_TIME Date and time with ZoneId '2011-12-03T10:15:30+01:00[Europe/Paris]'
ISO_ORDINAL_DATE Year and day of year '2012-337'
ISO_WEEK_DATE Year and Week '2012-W48-6'
ISO_INSTANT Date and Time of an Instant '2011-12-03T10:15:30Z'
RFC_1123_DATE_TIME RFC 1123 / RFC 822 'Tue, 3 Jun 2008 11:05:30 GMT'

 

이 포맷을 가지고 이렇게 사용할 수 있다. 

val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ISO_LOCAL_DATE
val formatted = current.format(formatter)

Log.d("formatted",formatted)

그리고 formatter에 지원하는 형식 말고도 

val formatter = DateTimeFormatter.ofPattern("yyyy년도 MM월 dd일의  HH시 mm분 ss초")

이렇게 내 마음대로 만들수 있다.

결과>

formatted      2023년도 04월 03일의  05시 29분 44초

728x90
반응형

댓글