Calculate Daily Streaks Across Daylight Saving Time

A daily reading streak looks like a simple counter. Read today, add one. Miss a day, start over.

Then someone reads late on Saturday, early on Sunday, and changes time zones on Monday. Our “subtract 86,400 seconds” implementation starts making decisions the user never agreed to.

The first fix is to define what a day means for the feature. The second is to calculate with that calendar instead of treating every day as an equal number of seconds.

Dave DeLong’s work on the sharp edges of calendrical code is a good reminder that familiar words like “day” need a precise representation. We can handle this particular problem with Foundation, using the completion dates the app already has.

Write down the streak rule first

For this reading app, let’s use the following policy:

  • Multiple completions on one calendar day count once.
  • A completion today extends the streak.
  • If today is unfinished, a streak ending yesterday remains current.
  • A missed day before today breaks the streak.
  • Future-dated completions do not count.

That third rule matters. At 8 a.m., the user still has time to read today. We should not erase a month-long streak merely because they have not opened their book yet.

This is a display calculation for already-authorized local data. There is no need to add a database trigger or a stored counter for it. If the product awards something that requires trusted enforcement, validate the qualifying events separately; the UI calculation should not become the authority for that award.

Choose a calendar and a time zone

A Date represents an instant. The calendar and time zone tell us which day contains that instant. Apple’s calendar calculation guide distinguishes calendar arithmetic from simply subtracting time intervals.

For an account whose streak follows a fixed home time zone, construct that policy explicitly:

import Foundation

let accountTimeZone = TimeZone(identifier: "America/Denver")!
var streakCalendar = Calendar(identifier: .gregorian)
streakCalendar.timeZone = accountTimeZone

Here, accountTimeZone is a validated TimeZone supplied by the account settings. An app that intentionally follows the user’s current calendar can pass a snapshot of Calendar.current instead. Both can be reasonable; silently switching between them is the problem.

Time-zone and daylight-saving changes affect the local interpretation of an instant. They do not, by themselves, change the underlying Date value. Keep the recorded instant intact and apply the chosen policy when grouping it.

Count consecutive day boundaries

Here is the complete calculation:

import Foundation

func currentStreak(
    completions: [Date],
    now: Date,
    calendar: Calendar
) -> Int {
    let completedDays = Set(
        completions
            .filter { $0 <= now }
            .map { calendar.startOfDay(for: $0) }
    )

    let today = calendar.startOfDay(for: now)
    var cursor = today

    if !completedDays.contains(today) {
        guard
            let yesterday = calendar.date(
                byAdding: .day, value: -1, to: today
            )
        else {
            return 0
        }
        cursor = calendar.startOfDay(for: yesterday)
    }

    var count = 0
    while completedDays.contains(cursor) {
        count += 1

        guard
            let previous = calendar.date(
                byAdding: .day, value: -1, to: cursor
            )
        else {
            break
        }
        cursor = calendar.startOfDay(for: previous)
    }
    return count
}

startOfDay(for:) gives each completion a common representative for its day. The set then removes duplicate days naturally. Use the calendar’s start-of-day API rather than assembling a midnight string; historical time-zone transitions do not always make midnight as ordinary as we expect.

Walking backward uses .day calendar arithmetic. We never assume the interval between successive boundaries is 24 hours.

Passing now also makes the calculation repeatable. The function does not sample the clock again halfway through its work, and tests do not depend on whatever day the CI machine happens to run them.

The input filter happens before grouping. That keeps a record scheduled for later today from counting as an already-completed activity just because it shares today’s day boundary.

Test short and long days on purpose

For test fixtures, use a fixed calendar and named time zone. These assertions demonstrate why a duration-based implementation is a poor fit:

var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(identifier: "America/Denver")!

@MainActor
func fixture(_ month: Int, _ day: Int) -> Date {
    calendar.date(
        from: DateComponents(
            year: 2026, month: month, day: day, hour: 12
        ))!
}

let springStart = calendar.startOfDay(for: fixture(3, 8))
let springEnd = calendar.startOfDay(for: fixture(3, 9))
assert(springEnd.timeIntervalSince(springStart) == 23 * 60 * 60)

let fallStart = calendar.startOfDay(for: fixture(11, 1))
let fallEnd = calendar.startOfDay(for: fixture(11, 2))
assert(fallEnd.timeIntervalSince(fallStart) == 25 * 60 * 60)

The force unwraps are limited to known test fixtures. User-entered calendar components and unknown time-zone identifiers need validation in production.

Next, put completions on March 7, 8, and 9, and evaluate after the March 9 completion. The answer should be three. Evaluate on March 10 before completing anything, and it should still be three. Evaluate on March 11 with no new completions, and it should be zero.

September 2026 review: those cases passed in the executable Swift 6.4 example, along with the November transition, February 29 in 2024, repeated completions on one day, empty input, and future-record exclusion. The November dates are deliberate test fixtures, not a claim that the app was tested on that future date.

Travel is a product decision

Suppose someone completes a session at an instant that is Monday in Tokyo and Sunday in Los Angeles. Reinterpreting every historical event in the user’s newest time zone can move a completion between days. That may change the streak even though no data was lost.

Pick the behavior you want before trying to fix it with more arithmetic:

PolicyWhat to preserve
Fixed account time zoneThe account’s chosen zone and each completion instant.
Current local time zoneThe instants, with an explicit expectation that travel can regroup history.
Day as recorded during completionA validated day identity plus the calendar/time-zone policy used to create it.

The function above implements the first two policies by regrouping instants with the supplied calendar. The third needs a different stored model; do not pretend a timestamp alone records the user’s original local-day intent.

Refresh the answer when its inputs change

Recalculate after completion data changes and when the relevant day changes. Also refresh when the scene becomes active, because the app may have been suspended across midnight. If your policy follows the system calendar or time zone, changes to those settings are inputs too.

For a small local completion history, this is inexpensive: build the set once per relevant change, then walk the current streak. Avoid recalculating it in every row’s body. For a large history, query the necessary records deliberately and ensure your pagination can extend past the current streak; an arbitrary 30-day fetch cannot prove a 100-day streak.

The useful part of this approach is that the counter becomes a consequence of the data and a written rule. When someone asks why their streak changed, we can explain which calendar days counted instead of trying to reconstruct a chain of increments and resets.