1. Calendar and time scale
Naljja-reul cheoeum-euro 다루기 sijakhals ttae-neun, naljja wa sigan-eun gateun geos-igo geunyang “jeongmilseong-i dareun geos”irago saenggakhagi swip습니다. Hajiman programming-eseoneun i geos-i dua gae-ui dareun uimiro, dareun chug-imnida: kalender-neun “eoneu nal?”eul, time scale-eun “eoneu sungan?”eul dae답합니다. Ireul gubunhaji anh-eumyeon, 1-nyeon-e du beon (geurigo haneun geot-cheoreom, prod-eseo)man teojineun bug-reul eokge doemnida.
Du gae-ui jeonhyeongjeog-in yogu-reul sangsanghae bopsida:
- “2026-02-01 kkaji gyeolje”reul mandeul ttae, i geos-eun kalender naljjaimnida. I ttaeneun LocalDate-ga mat습니다. i yu-neun cho/cho-danwi wa time zone-i anira, kalender-ui “geu nal”jachega jungyohagi ttaemunimnida.
- “sagyeon-i 2026-02-01T10:15:30Ze balsaeng했다”reul mandeul ttae, i geos-eun sigan-ui sunganimnida. I ttaeneun Instant-ga pilyohamnida. modu-ege gateun time scale-sang-ui jijeom-i jungyohagi ttaemunimnida.
I gang-ui haeksim-eul han munjang-euro 요약haemyeon ireoh습니다: kalender sdeugi(neun) LocalDate + DatePeriod-reul tonghae 하고, sungan-gwa sungan sai-ui gil-i 측정-eun Instant wa Duration-euro 합니다. Geuligo, saram-ege “haru-neun 24-sigan”cheoreom 느껴져do, i geos-eun jeonhyeolhi dareun geot-imnida.
2. DatePeriod and Duration
Duration-i “eolmana sigan-i jina-ssneunji”reul 초/밀리초/시간 단위로 나타낸다면, DatePeriod-eun “kalender-reul eolmana 옮길ji”reul 년/월/일 단위로 나타냅니다. I goteun danji ireum-eul oewuneun geosboda, i geos-i dua gae-ui dareun matematika-im-eul neukkineun geosi jungyohamnida.
- Duration-eun pyeongtanhan segye-imnida: 1-sigan-eun hangsang 60-bun, 1-bun-eun hangsang 60-cho. jajeonghan “ja”cheoreom seonhyeong-imnida.
- Kalender segye-neun pyeongtan하지 않습니다: han dal-eun 28, 29, 30, 31-il i doel su it습니다. geurigo time zone jeonhwan wa DST (haebit sigan/표준 시간) ttaemun-e, teukjeong “naljja + sigan”i yesangchi mothage dongjakhal su it습니다. pyeongsoeneun ja-ji man, gakkeum “akkordeon(garimosh)”cheoreom 늘었다 줄었다 하는 ja-cheoreom-yo.
Da-eum tab-eul meoritsog-e du-myeon yuyong합니다:
| Munje | Olbareun type | Olbareun “arithmetic” |
|---|---|---|
| “Silhaeng-e eolmana geollyeoss-eo?” | |
|
| “Choigeun 7-ilgan-ui 지출-eul (kalender-ro) boyeo jwo” | |
|
| “1-dal hu 구독-eul yeonjanghae” | |
|
| “24-sigan hu 알림-eul bonae” | |
|
Jigeum jageun hajiman jungyohan code style bogo-reul hana haess-eumnida. Hamseureul jageonghal ttae Kotlin-eun ilkgi swipge signeocheo-reul sseugo, yeoreo jul parameter-reul kkalkkeumhi formattingha-neun geos-eul jangryeo합니다 — i geos-eun “han argument silsu”ga naneun hwakryul-eul juligo, mirae-ui jasin-ege do code-reul deo chinjeolhage man듭니다. I style-eun hamseu formatting-e gwanhan gongshik hyeobui-gwa-do jal mat습니다.
3. Calendar shifts in LocalDate
“+ 1-il” tto-neun “- 2-dal”cheoreom kalender-ro 옮기고 싶다면, olbareun 도구-neun DatePeriod입니다. kotlinx.datetime (i kurs-eseo sayonghaneun sujun)eseoneun i geos-i aju nareum yepp게 bo입니다: DatePeriod(...)-reul mandeulgo, geugeos-eul LocalDate-e deo-hageona bbae-myeon 됩니다.
Gajang dan순han geotbuteo: + 1-il.
import kotlinx.datetime.DatePeriod
import kotlinx.datetime.LocalDate
fun main() {
val d = LocalDate.parse("2026-01-31")
val next = d + DatePeriod(days = 1)
println(d) // 2026-01-31
println(next) // 2026-02-01
}
Yeogineun jal ara듣neun “kalender 논리”ga jageong합니다: 1-wol 31-il + 1-il = 2-wol 1-il. sigan, bun, “i haru-e cho-ga myeot gae?” 같은 geos-eun amugeotdo eobs습니다.
Ida-eum-eun “- 1-ju” (kalender-eseo 1-ju-neun geunyang 7-il):
import kotlinx.datetime.DatePeriod
import kotlinx.datetime.LocalDate
fun main() {
val d = LocalDate.parse("2026-01-14")
val weekAgo = d - DatePeriod(days = 7)
println(weekAgo) // 2026-01-07
}
Geuligo “wol”euro deureogaseomyeon, wae kalender arithmetic-eul tteor-eo-naeseo byeoldo-ro 다루-neunji-ga deureonam니다.
import kotlinx.datetime.DatePeriod
import kotlinx.datetime.LocalDate
fun main() {
val d = LocalDate.parse("2026-01-31")
val nextMonth = d + DatePeriod(months = 1)
println(nextMonth) // (result depends on calendar rules)
}
Wae yeogie jeonghwakhan naljja-reul comment-ro an sseossneunji? i yu-neun “gyeolgwa”boda “uimi”ga deo jungyohagi ttaemunimnida: “+ 1-dal”eun “+ 30-il”i 아닙니다. I geos-eun “다음 달로 옮기되, kalender gyuchik-e 따라 가급적 ‘il-ja’(day-of-month)-reul 유지한다”는 뜻입니다. Siljeon-eseoneun yeogi-seo munje yogu-reul jeonghwakhi ara야 합니다: business-ga “다음 달의 마지막 날”, “가능하면 같은 날짜 번호”, “아니면 30일 이동” 중 어느 것을 원하는지에 따라 로직이 전혀 달라집니다.
Days vs duration: two different meanings
Program-eul jageonghal ttae, brains-eun gakkeum gyemyo한 chimyomhan 바꿔치기-reul 합니다: “1-il hu”reul bomyeon, son-i Durationeuro gam니다. “il”i 24-sigancheoreom deullyeo-seo-yo. Hajiman kalender-eseo “il”eun 24*60*60-cho-ga 아니라, naljja-ga bakkwigo 넘어가는 것입니다.
- “naeil kkeutkkaji deadline” scenarioneun daebubun kalender-imnida: user-ege “naeil”i 되기를 바라며, geu nal-e haru-ga myeot sigan-indo (spoiler: gakkeum 24-ga 아닙니다) sanggwan-eops습니다.
- “haru (24-sigan) gidarida가 요청 보내기” scenarioneun duration-imnida. geureomyeon Duration-i jeongmal 맞습니다.
Chai-reul deo jal neukkineun geot-eul wihayeo, dua gae-ui function-eul bigyohae bopsida: hana-neun “+ 7 kalender il”, dareun hana-neun “+ 7 * 24-sigan”입니다.
import kotlinx.datetime.DatePeriod
import kotlinx.datetime.LocalDate
fun add7CalendarDays(date: LocalDate): LocalDate {
return date + DatePeriod(days = 7)
}
import kotlinx.datetime.Instant
import kotlin.time.Duration.Companion.days
fun add7x24Hours(instant: Instant): Instant {
return instant + 7.days
}
Dua function da yuyong합니다. Danji dareun munjee dae답합니다. Ireul hon동hamyeon, “gakkeum” teojineun bug-reul eokge doemnida. Geuligo programming-eseo “gakkeum”eun “사용자가 반드시 잡아낸다”로 번역됩니다.
4. Start of day and converting to Instant
Kalender naljja (LocalDate)reul sigan-ui sungan (Instant)uro 바꾸려는 순간, time zone-eul 반드시 seontaekhaeya 합니다. Wae냐하면 “2026-01-14 00:00” in Tokyo wa “2026-01-14 00:00” in New York-eun time scale-sang-ui dareun sungan-igi 때문입니다.
Ilsang-e-seoneun “haru-ui sijak”eul 말하면, geuge bo편적인 한 점인 것처럼 들립니다. Hajiman programming-eseoneun bo편적인 점이 아니라 규칙입니다: “i zone-eseo i kalender nal-ui start-of-day-ga eotteon instant-e 해당한다.”
kotlinx.datetimeeseoneun 이를 wihan 편한 function-i 있습니다: atStartOfDayIn(timeZone).
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn
fun main() {
val date = LocalDate.parse("2026-01-14")
val startUtc = date.atStartOfDayIn(TimeZone.UTC)
println(startUtc) // 2026-01-14T00:00:00Z
}
Yeogiseo point: LocalDate jache-eun haru jung eoneu sigan인지가 eops고, atStartOfDayIn(...)i 말합니다: “OK, i zone-eseo haru-ui start-reul 00:00로 보고, Instant로 변환하자.”
Da-eumcheoreom 시각화하면 aju yuyong합니다:
flowchart LR
A["LocalDate: 2026-01-14
calendar date"] -->|"atStartOfDayIn(TimeZone)"| B["Instant
a moment on the time scale"]
B -->|"toLocalDateTime(TimeZone)"| C["LocalDateTime
local wall-clock time"]
Yeogiseo haeksim uimi-neun: TimeZoneeun 다리입니다. dari-ga eopseumyeon gang byeon-e seoseo u울해지거나 (tto-neun hacky workaround-reul sseu-go, geu daeum-e deo u울해집니다).
From LocalDateTime to Instant
Jaju balsaenghaneun s황: user-ro부터 “byeok-gye sigye” 같은 로컬 시각을 받습니다. 예를 들어 2026-01-14T10:00:00. I geos-eun LocalDateTime입니다. Hajiman 이를 “sungan”으로 바꾸려면, 10-si-ga eodi서의 10-si인지 알아야 합니다.
kotlinx.datetimeeseo 변환은 이렇게 합니다: localDateTime.toInstant(timeZone).
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
fun main() {
val ldt = LocalDateTime.parse("2026-01-14T10:00:00")
val instantUtc = ldt.toInstant(TimeZone.UTC)
println(instantUtc) // 2026-01-14T10:00:00Z
}
System zone-eul neomgimyeon, “program-i dongjakjung-in machine-ui local rule-e 따른 10:00”에 해당하는 순간을 얻게 됩니다.
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
fun main() {
val ldt = LocalDateTime.parse("2026-01-14T10:00:00")
val tz = TimeZone.currentSystemDefault()
val instant = ldt.toInstant(tz)
println(instant) // depends on tz
}
Wae i geosi jungyohan-ga-yo? “system zone”eun 숨은 의존성입니다. Oneul-eun program-i nae notebook-eseo, naeil-eun dareun zone-ui server-eseo, moreuneun nal-eun user-ga chuljang jung-in gote-seo 실행될 수 있습니다. Zone-i uimi-e yeonghyang-eul 준다면, “eotteokha-myeon doeg겠지”를 기대하기보다 TimeZone-eul parameter-ro 명시적으로 전달하는 게 낫습니다.
DST and why a day is not always 24 hours
I 부분은 time zone 전문가가 되라는 뜻이 아닙니다. “비선형인 곳에서 시간을 선형으로 착각하지 말자”를 위해 필요합니다.
DST (daylight saving / standard time switching)란, 일부 지역에서 특정 날짜에 시계가 앞으로 또는 뒤로 “점프”하는 상황입니다. 그 결과 로컬 시간에는 “한 시간이 사라지는 짧은 하루”와 “한 시간이 반복되는 긴 하루”가 존재할 수 있습니다.
Siljeon-eseo mwoseul uimiha나-yo? LocalDate 두 개(이웃한 날짜)에 대해 atStartOfDayIn(tz)로 Instant를 얻고, 그 둘을 빼서 Duration을 구하면, 정확히 24시간이 아닐 수 있습니다. 그런데 이것은 jeong상입니다. kalender-neun 로컬 규칙에 따라 움직이기 때문입니다.
이 코스에서는 규칙 하나만 기억하면 충분합니다: “다음 kalender nal”을 원하면 LocalDate + DatePeriod(days = 1); “24-sigan”을 원하면 Instant + 24.hours. 둘을 서로 대체하려고 하지 마세요 — “다음 페이지로”를 “300픽셀 스크롤”로 대체하려는 것과 비슷합니다: 가끔은 비슷해 보여도 의미가 다릅니다.
When you actually need “start of day”
여기서 질문이 생길 수 있습니다: 지출을 LocalDate로 저장한다면, 왜 굳이 atStartOfDayIn()와 Instant 변환이 필요할까요? 보통은 “진짜” 정렬과 경계 처리를 시작할 때 필요해집니다.
예를 들어 지출을 로그로 내보내고 싶은데, 로그 시스템은 모든 것을 순간(time instant)으로 저장한다면(동기화나 감사 목적 등). 또는 특정 zone에서 “정확히 자정부터” 지출을 비교하고 싶다면. 그때 “날짜”는 “순간”이 되어야 하고, 여기서 start-of-day 규칙이 등장합니다.
예를 들어, “주어진 zone에서 지출 날짜의 시작 순간을 얻기” 함수를 만들어 봅시다.
import kotlinx.datetime.Instant
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn
fun expenseStartInstant(expense: Expense, timeZone: TimeZone): Instant {
return expense.date.atStartOfDayIn(timeZone)
}
그리고 이 순간으로 지출을 정렬할 수도 있습니다(물론 LocalDate만으로도 정렬은 대개 쉽습니다). 핵심은 “zone에 대한 의존성”을 이제 명시적으로 만들고, 그 자정이 어디의 자정인지 “추측”하려 하지 않는다는 점입니다.
5. Practical example: dates in BudgetBuddy
이제 실용적(그리고 꽤 현실적인) 단계로 가봅시다: 학습용 콘솔 지출 관리 앱에 “거래의 kalender 날짜”를 추가하겠습니다. 앱 이름은 과하게 꾸미지 않고 소박하게: BudgetBuddy. 이전 챕터들에서 우리는 이미 지출 모델, 지출 목록, 커맨드, 리포트를 갖고 있습니다. 이제 지출이 단순히 “금액과 카테고리”가 아니라, “어느 날에”까지 포함하기를 원합니다.
Model: expense with LocalDate
간단한 모델부터 시작하겠습니다. 포인트: 우리는 LocalDate를 사용합니다. 일상적인 지출에서는 보통 “kalender 상의 날”(예: “1월 14일에 돈을 썼다”)이 중요하지, 정확한 Instant가 중요하지 않기 때문입니다.
import kotlinx.datetime.LocalDate
data class Expense(
val id: Int,
val amountCents: Int,
val category: String,
val date: LocalDate,
)
네, 돈은 센트 단위(Int)로 저장합니다. Double과 “소수점이 어디 있냐”로 싸우지 않기 위해서입니다(Double의 소수점은 보통 여러분이 가장 원치 않는 곳에 있습니다).
“Today” as LocalDate
우리는 “오늘”을 kalender 날짜로 필요로 합니다. 가장 직선적인 방법: Instant를 얻고, 시스템 zone을 통해 LocalDate로 바꾸는 것입니다.
import kotlinx.datetime.Clock
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
fun todayLocalDate(timeZone: TimeZone): kotlinx.datetime.LocalDate {
val now = Clock.System.now()
return now.toLocalDateTime(timeZone).date
}
여기엔 중요한 생각이 있습니다: “오늘”조차 zone에 따라 달라집니다. 어떤 zone에선 이미 1월 14일인데, 다른 zone에선 아직 13일일 수 있습니다. 그래서 timeZone을 parameter로 받아 의존성을 명시합니다.
Safe parsing of input date
이제 날짜 읽기 함수를 추가해 봅시다. 사용자는 ISO 형식 yyyy-MM-dd 문자열을 입력합니다(LocalDate.parse가 이해하기 때문). 우리는 LocalDate?를 반환합니다.
import kotlinx.datetime.LocalDate
fun parseLocalDateOrNull(input: String): LocalDate? {
val prepared = input.trim()
return runCatching { LocalDate.parse(prepared) }.getOrNull()
}
Contract는 단순합니다: 날짜가 올바르면 날짜, 아니면 null. 누군가 2026-13-40을 입력했다고 해서 프로그램이 죽으면 안 됩니다.
Expense date: empty → use “today”
추가 로직의 일부를 조립해 보겠습니다. 여기서는 “guard clauses”(early return)를 사용해 코드가 선형적으로 읽히게 합니다. 그리고 스타일 측면에서도, 이런 함수는 특히 parameter가 늘어날수록 깔끔하게 formatting하는 편이 보통 더 좋습니다 — Kotlin 코드의 일반적인 컨벤션과도 맞습니다.
import kotlinx.datetime.TimeZone
fun readExpenseDateOrToday(timeZone: TimeZone): kotlinx.datetime.LocalDate {
print("Date (yyyy-MM-dd), empty = today: ")
val s = readln().trim()
if (s.isEmpty()) return todayLocalDate(timeZone)
return parseLocalDateOrNull(s) ?: todayLocalDate(timeZone)
}
네, 여기엔 타협이 있습니다: 날짜가 잘못되면 조용히 오늘을 사용합니다. 실제 제품에서는 사용자에게 오류를 알려주는 편이 낫지만, 학습 예제에서는 괜찮습니다: 우리는 타입과 산술에 집중합니다.
Report: “last 7 calendar days”
이제 핵심: 오늘을 포함해 최근 7일의 지출을 출력하고 싶습니다. 이것은 순수한 kalender 논리입니다: “오늘”과 “6일 전”.
import kotlinx.datetime.DatePeriod
import kotlinx.datetime.TimeZone
fun last7DaysRange(timeZone: TimeZone): ClosedRange<kotlinx.datetime.LocalDate> {
val end = todayLocalDate(timeZone)
val start = end - DatePeriod(days = 6)
return start..end
}
이제 이 range를 목록에 적용해 봅시다.
import kotlinx.datetime.TimeZone
fun filterByDateRange(
expenses: List<Expense>,
timeZone: TimeZone,
): List<Expense> {
val range = last7DaysRange(timeZone)
return expenses.filter { it.date in range }
}
포인트: LocalDate는 kalender 기준으로 비교되고, start..end range는 사람이 읽기에도 매우 자연스럽습니다.
6. Common mistakes
Mistake 1: doing calendar shifts via Duration.
초보자들이 “+ 1 day”를 보고 + 24.hours를 쓰는 경우가 아주 많습니다. 가끔은 기대와 맞을 수도 있지만, 이것은 완전히 다른 의미입니다: 선형 시간축에서 “순간”을 이동시키는 것입니다. 문제가 “다음 kalender 날”을 원한다면 LocalDate + DatePeriod(days = 1)를 사용하세요. 그렇지 않으면 zone과 DST 효과가 튀어나오기 시작합니다.
Mistake 2: assuming “a month” equals “30 days”.
Kalender에는 그런 규칙이 없습니다. 달은 길이가 다르고, 가끔은 2월이 “서프라이즈”를 줍니다. 요구사항이 “한 달 후”라면 DatePeriod(months = 1)를 사용하고, 29/30/31일 같은 날짜에 대해 다음 달에 그 날짜가 없으면 어떻게 할지 business rule을 명확히 하세요.
Mistake 3: trying to get an Instant from LocalDate or LocalDateTime without a time zone.
LocalDate와 LocalDateTime에는 zone 정보가 없기 때문에, 하나의 “순간”으로 모호함 없이 결정될 수 없습니다. Instant가 필요하다면, zone을 명시적으로 선택하세요: date.atStartOfDayIn(tz) 또는 ldt.toInstant(tz). 이것은 까다로움이 아니라 숨은 버그를 막는 안전장치입니다.
Mistake 4: using TimeZone.currentSystemDefault() as a “magic constant” everywhere.
System zone은 환경 의존성이고, 컴퓨터와 서버가 바뀌면 달라집니다. Zone이 의미에 중요하다면(예: 보고서는 “사용자 시간” 기준으로 만들어져야 한다면), TimeZone을 parameter로 전달하세요. 그러면 코드가 테스트 가능하고 예측 가능해집니다.
Mistake 5: mixing “date” and “moment in time” in the same variable.
예를 들어 지출 날짜를 문자열 "2026-01-14T00:00:00Z"로 저장해 놓고, 나중에 substring(0, 10)으로 잘라서 “날짜를 얻으려는” 방식. 이것은 다시 문자열 기반의 임시방편 세계로 돌아가는 것입니다. 엔티티가 kalender 날짜라면 LocalDate로 저장하세요. 엔티티가 순간이라면 Instant로 저장하세요.
Mistake 6: expecting the difference between starts of adjacent days to always be 24 hours.
로컬 zone에서는 시간 전환 때문에 어떤 날은 한 시간 “짧아지거나”, “길어질” 수 있습니다. 이는 정상입니다. 따라서 “start of day + 24 hours”를 “다음 날”의 보편 공식으로 쓰지 마세요. Kalender에는 DatePeriod를, duration에는 Duration을 사용하세요.
GO TO FULL VERSION