1. The calendar and the timeline
When you first start working with dates, it’s very tempting to think that date and time are the same thing, just “with different precision.” But in programming these are two different axes of meaning: a calendar answers “which day?”, while a timeline answers “at which instant?” If you don’t separate them, you’ll get bugs that show up only twice a year (and, of course, in production).
Let’s imagine two typical requirements:
- If you’re doing “pay by 2026-02-01,” that’s a calendar date. LocalDate fits here, because the day on the calendar is what matters—not seconds and not a time zone.
- If you’re doing “the event happened at 2026-02-01T10:15:30Z,” that’s an instant in time. You need Instant here, because you care about a point on the timeline that is the same for everyone.
The main idea of the lecture in one sentence is this: do calendar shifts via LocalDate + DatePeriod, and measure durations between instants via Instant and Duration. And yes, these are different things, even if it feels to a human that “a day is 24 hours.”
2. DatePeriod and Duration
If Duration is “how much time has passed” in seconds/milliseconds/hours, then DatePeriod is “by how much to shift the calendar” in years/months/days. And the key here is not just memorizing the names, but feeling that these are two different kinds of math.
- With Duration, the world is flat: 1 hour is always 60 minutes, 1 minute is always 60 seconds. It’s like a ruler.
- With the calendar, the world is uneven: a month can have 28, 29, 30, or 31 days. Plus there are time-zone transitions and DST (daylight saving time), because of which a specific “date + time” can behave unexpectedly. It’s like a ruler that sometimes turns into an accordion.
It’s useful to keep a table like this in mind:
| Task | Correct type | Correct “arithmetic” |
|---|---|---|
| “How long did it take to run?” | |
|
| “Show spending for the last 7 days (calendar-wise)” | |
|
| “Extend the subscription in 1 month” | |
|
| “Send a notification in 24 hours” | |
|
A quick but important note about code style. When you write functions, Kotlin encourages readable signatures and neat formatting of multi-line parameters—this reduces the chance of an “off-by-one-argument” mistake and makes the code friendlier to your future self. This style aligns well with the official function formatting conventions.
3. Calendar shifts in LocalDate
When you want “plus one day” or “minus two months,” the right tool is DatePeriod. In kotlinx.datetime (at the level used in this course) it looks very nice: you create DatePeriod(...) and add or subtract it from LocalDate.
Let’s start with the simplest: plus one day.
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
}
Here the intuitive “calendar logic” works: January 31 + 1 day = February 1. No hours, minutes, or “how many seconds are in that day.”
Now “minus a week” (a calendar week is just 7 days on the calendar):
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
}
And with months we get to the reason calendar arithmetic is a separate tool in the first place.
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)
}
Why didn’t I write a comment with the exact date here? Because it’s more important to understand the meaning: “plus one month” is not “plus 30 days”. It means “move to the next month, keeping the day-of-month as much as possible according to calendar rules.” In practice, this is where you must understand the product requirements: the business may want “the last day of the next month,” “the same day number if it exists,” or “a 30-day shift”—and those are three different rules.
Days and duration: two different meanings
When you write a program, your brain often makes a sneaky substitution: if you see “in 1 day,” your hand reaches for Duration, because “day” sounds like 24 hours. But for the calendar, a “day” is a date change, not 24*60*60 seconds.
- The scenario “deadline by the end of tomorrow” is almost always calendar-based: you want it to be “tomorrow” on the calendar, regardless of how many hours the user’s day has (spoiler: sometimes it’s not 24).
- The scenario “wait 24 hours and make a request” is a duration. Duration is appropriate there.
To better feel the difference, let’s compare two functions: one does “plus 7 calendar days,” the other does “plus 7 * 24 hours.”
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
}
Both functions are useful. They just answer different questions. If you mix them up, you’ll get a bug that shows up “sometimes.” And “sometimes” in programming translates to “the user will definitely catch it.”
4. Start of day and converting to Instant
As soon as you want to turn a calendar date (LocalDate) into an instant in time (Instant), you must choose a time zone. Because “2026-01-14 00:00” in Tokyo and “2026-01-14 00:00” in New York are different points on the timeline.
In everyday speech we say “start of day” as if it were a universal point. In programming it’s not universal; it’s a rule: “in this zone, the start of this calendar day corresponds to this instant.”
In kotlinx.datetime there is a handy function for this: 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
}
Notice the beauty: LocalDate by itself contains no time-of-day, and atStartOfDayIn(...) says: “OK, assume the start of the day is 00:00 in this zone, and convert it to an Instant.”
It’s very useful to visualize it like this:
flowchart LR
A["LocalDate: 2026-01-14
calendar date"] -->|"atStartOfDayIn(TimeZone)"| B["Instant
point in time on the timeline"]
B -->|"toLocalDateTime(TimeZone)"| C["LocalDateTime
local clock time"]
The key idea here: TimeZone is a bridge. Without the bridge you’re stuck on the shore feeling sad (or writing hacks, and then feeling even sadder).
From LocalDateTime to Instant
A common situation: you get a local “wall clock time” from the user, for example 2026-01-14T10:00:00. This is LocalDateTime. But to turn it into an “instant,” you need to understand: 10 a.m. where?
In kotlinx.datetime the conversion is done like this: 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
}
If you plug in the system time zone, you’ll get the instant that corresponds to “10:00 according to the local rules of the machine running the program.”
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
}
Why does this matter? Because the “system time zone” is a hidden dependency. Today the program runs on your laptop, tomorrow on a server in another zone, and the day after tomorrow on a user’s machine while traveling. If the zone affects meaning, it’s better to pass TimeZone explicitly as a parameter rather than hoping it will “work out somehow.”
DST and why a day is not always 24 hours
This section is not here to make you a time zone expert. It’s here to stop you from treating time as linear where it isn’t.
DST (daylight saving time) is when, in some regions, on a certain day the clock “jumps” forward or backward. Because of this, in local time there can be “short days” where an hour disappears, and “long days” where an hour repeats.
What does this mean in practice? If you take a LocalDate, call atStartOfDayIn(tz) for two adjacent dates, and subtract them as Instants, you may get a Duration that is not exactly 24 hours. And that is normal, because the calendar lives by local rules.
For this course it’s enough to remember one rule: if you want “the next calendar day,” use LocalDate + DatePeriod(days = 1); if you want “24 hours,” use Instant + 24.hours. Don’t try to replace one with the other—it’s like replacing “go to the next page” with “scroll 300 pixels”: sometimes it looks similar, but the meaning is different.
When you actually need “start of day”
A question might come up: if we store expenses as LocalDate, why do we need atStartOfDayIn() and conversion to Instant at all? It usually appears exactly when you start doing “real” sorting and boundaries.
Imagine you want to export expenses into a log where everything is stored as instants (for example, for synchronization or auditing). Or you want to compare expenses “strictly starting from midnight” in a specific zone. Then a “date” has to become an “instant,” and that’s where the start-of-day rule comes in.
For example, let’s make a function: “get the instant at the start of the expense day” in a given 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)
}
And you can sort expenses by these instants (although sorting LocalDate is usually straightforward anyway). But the point is that you now make the zone dependency explicit and don’t try to “guess” where that midnight is.
5. Practical example: dates in BudgetBuddy
Now let’s take a practical (and very realistic) step: add a “calendar date of the operation” to our educational console expense-tracking app. Let’s keep the name modest and without pomp: BudgetBuddy. In previous chapters of the course we already have an expense model, a list of expenses, commands, and reports. Now we want an expense to be not just “amount and category,” but also “on which day.”
Model: an expense with LocalDate
Let’s start with a simple model. Note: we use LocalDate, because for expenses in the everyday sense the calendar day usually matters (“I spent money on January 14”), not the exact Instant.
import kotlinx.datetime.LocalDate
data class Expense(
val id: Int,
val amountCents: Int,
val category: String,
val date: LocalDate,
)
Yes, we store money in cents (Int) to avoid arguing with Double about where its decimal point is (with Double, the decimal point is usually exactly where you least want it).
“Today” as LocalDate
We need “today” as a calendar date. The most direct way: take an Instant and convert it to LocalDate through the system time zone.
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
}
There’s an important idea here: even “today” depends on the time zone. When it’s already January 14 in one zone, it’s still the 13th in another. So we accept timeZone as a parameter and make the dependency explicit.
Safe parsing of an input date
Now let’s add a date-reading function. The user enters a string in ISO format yyyy-MM-dd (because LocalDate.parse understands it), and we return LocalDate?.
import kotlinx.datetime.LocalDate
fun parseLocalDateOrNull(input: String): LocalDate? {
val prepared = input.trim()
return runCatching { LocalDate.parse(prepared) }.getOrNull()
}
The contract is simple: either the date is valid, or null. No program crashes just because someone typed 2026-13-40.
Expense date: empty → use “today”
Let’s assemble the add-flow logic. Here we use guard clauses (early returns) so the code reads linearly. And yes, style-wise it’s usually better to format such functions neatly, especially when parameters start to grow—this matches common Kotlin code conventions.
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)
}
Yes, there’s a trade-off here: if the date is invalid, we silently take today. In a real product it’s better to tell the user about the error, but for an educational example this is fine: we’re focusing on types and arithmetic.
Report: “last 7 calendar days”
Now the most interesting part: we want to print expenses for the last 7 days, including today. This is pure calendar logic: “today” and “six days ago.”
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
}
Now let’s apply the range to the list.
import kotlinx.datetime.TimeZone
fun filterByDateRange(
expenses: List<Expense>,
timeZone: TimeZone,
): List<Expense> {
val range = last7DaysRange(timeZone)
return expenses.filter { it.date in range }
}
Note: LocalDate is compared calendar-wise, and the range start..end reads very naturally.
6. Common mistakes
Mistake #1: doing calendar shifts via Duration.
Very often a beginner sees “plus one day” and writes + 24.hours. Sometimes it matches expectations, but it’s a completely different semantics: you’re shifting an instant on a linear timeline. If the task requires “the next calendar day,” use LocalDate + DatePeriod(days = 1), otherwise time-zone and DST effects will start surfacing.
Mistake #2: assuming “a month” equals “30 days.”
The calendar has no such rule. Months have different lengths, and sometimes February has a surprise. If the requirement is “in a month,” use DatePeriod(months = 1) and clarify the business rule for dates like the 29th/30th/31st (what to do if that day doesn’t exist next month).
Mistake #3: trying to get an Instant from LocalDate or LocalDateTime without a time zone.
LocalDate and LocalDateTime don’t contain zone information, so they cannot unambiguously become an “instant.” If you need an Instant, choose the zone explicitly: date.atStartOfDayIn(tz) or ldt.toInstant(tz). This isn’t pedantry; it’s protection against hidden bugs.
Mistake #4: using TimeZone.currentSystemDefault() as a “magic constant” everywhere.
The system time zone is an environment dependency; it changes between computers and servers. If the zone matters for meaning (for example, a report must be built “in the user’s time”), pass TimeZone as a parameter. This makes your code testable and predictable.
Mistake #5: mixing “date” and “instant in time” in the same variable.
For example, storing an expense date as the string "2026-01-14T00:00:00Z" and then trying to cut out substring(0, 10) “to get the date.” This takes you back to the world of string hacks. If the entity is a calendar date, store LocalDate. If the entity is an instant, store Instant.
Mistake #6: expecting the difference between the start of adjacent days to always equal 24 hours.
In local zones, because of time shifts, there are days that are “shorter” or “longer” by an hour. That’s normal. So don’t use “start of day + 24 hours” as a universal formula for “the next day.” For the calendar use DatePeriod; for duration use Duration.
GO TO FULL VERSION