Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

Day-model follow-ups: the review findings deferred from #97 (#98)

Carterefb6f54c314f
diff --git a/.gitignore b/.gitignore
index a4a3ec8..7ed2226 100644
--- a/.gitignore
+++ b/.gitignore
@@ -48,10 +48,14 @@ temp/
# design docs (keep screenshots for README). Pre-build planning notes — wireframes,
# MVP scope, stack bake-offs — stay local: they described intentions, and the code is
-# now the truth. docs/TESTING.md is the exception: it documents how to run the suite
-# and CONTRIBUTING.md links to it, so it stays tracked.
+# now the truth. The exceptions are the ones another tracked file tells you to read:
+# docs/TESTING.md (linked from CONTRIBUTING.md) documents how to run the suite, and
+# docs/API_CHANGES.md (linked from RELEASING.md) carries breaking API changes into the
+# next release's notes — a release process that depends on an untracked file is one that
+# silently stops working for everyone but its author.
docs/*.md
!docs/TESTING.md
+!docs/API_CHANGES.md
docs/*.txt
# Local Claude context
@@ -80,3 +84,10 @@ web/playwright-report/
# MCP server config: machine-specific absolute paths, not portable across checkouts.
.mcp.json
+
+# Maestro flows are local-only dev artifacts, same call as 5fc269a ("remove stray
+# Maestro flow committed with #61"). Nothing in CI runs them — they need a device and
+# a running backend — so a committed flow is a file that rots without anyone noticing.
+# The rule exists because the convention alone did not hold: without it the same mistake
+# landed twice, and the second time it reached main.
+mobile/.maestro/
diff --git a/RELEASING.md b/RELEASING.md
index b556ef7..56a0b09 100644
--- a/RELEASING.md
+++ b/RELEASING.md
@@ -75,11 +75,19 @@ gh release create v0.1.0-beta.4 --target main --prerelease --notes-file notes.md
gh release edit v0.1.0-beta.4 --notes-file notes.md
```
+Check `docs/API_CHANGES.md` first — it holds any breaking HTTP API change that landed
+since the last release, written down when it merged so it can't be forgotten here. Fold
+each entry into the notes under "Breaking changes", then delete it from that file.
+
Template — no emoji, keep it simple:
```markdown
One-line summary of the release.
+## Breaking changes
+
+- What changed and what a caller must send instead (#123)
+
## What's new
**Feature name** (#123)
diff --git a/backend/controllers/weight_test.go b/backend/controllers/weight_test.go
index e9863e6..2d1439b 100644
--- a/backend/controllers/weight_test.go
+++ b/backend/controllers/weight_test.go
@@ -650,3 +650,102 @@ func insertWeightLogOn(t *testing.T, uid int64, weight float64, day, loggedAt st
t.Fatalf("insert weight log: %v", err)
}
}
+
+// A row the backfill could not date must not distort the summary or vanish from
+// windows. logged_on defaults to ”, which sorts before every real date: read raw, an
+// unset row is simultaneously the "starting" weight (first ASC) and never the "latest"
+// (last DESC), and `logged_on >= ?` hides it from every range. Reads fall back to the
+// instant's own date so it lands in one sensible place instead of two wrong ones.
+//
+// The unset row here carries the LATEST instant, so the two rules disagree: raw makes
+// it oldest, the fallback makes it newest.
+func TestWeightReads_unsetDayFallsBackToTheInstant(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ insertWeightLogOn(t, uid, 200.0, "", "2026-08-09T12:00:00Z") // unset day, newest instant
+ insertWeightLogOn(t, uid, 170.0, "2026-08-05", "2026-08-05T12:00:00Z") // dated, older
+
+ c, w := newContext(uid, http.MethodGet, "/api/v1/weight/stats", nil)
+ th.GetWeightStats(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("stats: expected 200, got %d", w.Code)
+ }
+ stats := decodeResponse(t, w)["data"].(map[string]any)
+ if got := stats["latest"].(float64); got != 200.0 {
+ t.Errorf("latest weight = %v, want 200 (the newest day, not the one with a blank logged_on)", got)
+ }
+ if got := stats["starting"].(float64); got != 170.0 {
+ t.Errorf("starting weight = %v, want 170 (a blank logged_on must not sort before every real date)", got)
+ }
+
+ // And the same row must still be reachable through a day range that contains it.
+ c, w = newContext(uid, http.MethodGet, "/api/v1/weight?from=2026-08-08&to=2026-08-10", nil)
+ th.ListWeightLogs(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("list: expected 200, got %d", w.Code)
+ }
+ data := decodeResponse(t, w)["data"].([]any)
+ if len(data) != 1 {
+ t.Fatalf("range returned %d entries, want 1 — an undated row dropped out of its own window", len(data))
+ }
+}
+
+// A row whose instant cannot be read must not outrank every dated row.
+//
+// The fallback slices logged_at for a row with no stored day — but the only rows that
+// reach it are the ones the backfill could not read, so the slice returns text like
+// 'not-a-tim'. In SQLite's collation that sorts AFTER every real date, which made an
+// unreadable row the permanent "latest" weight on the dashboard. Yielding NULL keeps it
+// out of the answer rather than putting it at the front of the queue.
+func TestWeightStats_unreadableInstantNeverBecomesLatest(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ insertWeightLogOn(t, uid, 999.0, "", "not-a-timestamp")
+ insertWeightLogOn(t, uid, 170.0, "2026-08-05", "2026-08-05T12:00:00Z")
+
+ c, w := newContext(uid, http.MethodGet, "/api/v1/weight/stats", nil)
+ th.GetWeightStats(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+ stats := decodeResponse(t, w)["data"].(map[string]any)
+ if got := stats["latest"].(float64); got != 170.0 {
+ t.Errorf("latest = %v, want 170 — an unreadable instant sorted above every real date", got)
+ }
+ if got := stats["starting"].(float64); got != 170.0 {
+ t.Errorf("starting = %v, want 170", got)
+ }
+}
+
+// The same garbage must never reach a client as a history point's date: every client
+// feeds that string to dayToLocalDate, and an Invalid Date makes the formatter throw,
+// taking down the whole nutrition page rather than mislabelling one bar.
+func TestFoodHistory_neverReturnsANonDate(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ if _, err := db.DB.Exec(
+ `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, servings, logged_at, logged_on)
+ VALUES (?, 'unreadable', 'lunch', 100, 0, 0, 0, 1, 'not-a-timestamp', '')`, uid); err != nil {
+ t.Fatalf("seed unreadable food: %v", err)
+ }
+ if _, err := db.DB.Exec(
+ `INSERT INTO food_logs (user_id, name, meal, calories, protein, carbs, fat, servings, logged_at, logged_on)
+ VALUES (?, 'good', 'lunch', 200, 0, 0, 0, 1, '2026-08-05T12:00:00Z', '2026-08-05')`, uid); err != nil {
+ t.Fatalf("seed good food: %v", err)
+ }
+
+ c, w := newContext(uid, http.MethodGet, "/api/v1/food/history?days=3650", nil)
+ th.GetFoodHistory(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+ for _, p := range decodeResponse(t, w)["data"].([]any) {
+ day := p.(map[string]any)["date"].(string)
+ if _, err := time.Parse("2006-01-02", day); err != nil {
+ t.Errorf("history returned %q as a date — clients parse this and the page throws", day)
+ }
+ }
+}
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index a8e85f0..8402cea 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -85,6 +85,7 @@ func alterMigrations() {
normalizeWorkoutStartedAt()
normalizeFoodLoggedAt()
+ normalizeWeightLoggedAt()
// The day a diary entry belongs to, and the offset a workout started at, stored
// ON THE ROW instead of derived from the account's current zone at read time.
@@ -166,6 +167,28 @@ func backfillLocalDays() {
setMigrationFlag("backfill_local_days")
}
+// scanStoredTime reads a timestamp column whatever shape the driver hands back, and
+// reports whether it could be read at all.
+//
+// Shared by both backfills on purpose. They had the same bug and only one was fixed:
+// scanning straight into time.Time makes a single legacy value the driver cannot parse
+// fail the scan, and since the caller returns on error, one unreadable row abandoned the
+// rest of the upgrade and never set the completion flag — so every later boot retried and
+// failed identically. Keeping the read in one place is what stops that fix drifting apart
+// again.
+func scanStoredTime(v any) (time.Time, bool) {
+ switch tv := v.(type) {
+ case time.Time:
+ return tv, true
+ case string:
+ return parseStoredTime(tv)
+ case []byte:
+ return parseStoredTime(string(tv))
+ default:
+ return time.Time{}, false
+ }
+}
+
// backfillDayColumn sets table.logged_on from table.<column> resolved in the owning
// user's zone. Users with no settings row fall back to UTC, matching userLocation.
func backfillDayColumn(table, column string, loadLoc func(string) *time.Location) error {
@@ -183,12 +206,17 @@ func backfillDayColumn(table, column string, loadLoc func(string) *time.Location
var fixes []fix
for rows.Next() {
var id int64
- var at time.Time
+ var v any
var zone string
- if err := rows.Scan(&id, &at, &zone); err != nil {
+ if err := rows.Scan(&id, &v, &zone); err != nil {
rows.Close()
return err
}
+ at, ok := scanStoredTime(v)
+ if !ok {
+ log.Printf("backfillDayColumn(%s.%s): row %d: unreadable value %v left unset", table, column, id, v)
+ continue
+ }
fixes = append(fixes, fix{id, at.In(loadLoc(zone)).Format("2006-01-02")})
}
rows.Close()
@@ -240,12 +268,17 @@ func backfillWorkoutOffsets(loadLoc func(string) *time.Location) error {
var fixes []fix
for rows.Next() {
var id int64
- var at time.Time
+ var v any
var zone string
- if err := rows.Scan(&id, &at, &zone); err != nil {
+ if err := rows.Scan(&id, &v, &zone); err != nil {
rows.Close()
return err
}
+ at, ok := scanStoredTime(v)
+ if !ok {
+ log.Printf("backfillWorkoutOffsets: row %d: unreadable started_at %v left unset", id, v)
+ continue
+ }
_, offsetSeconds := at.In(loadLoc(zone)).Zone()
fixes = append(fixes, fix{id, offsetSeconds / 60})
}
@@ -296,6 +329,12 @@ func normalizeFoodLoggedAt() {
normalizeUTCTimestamps("normalize_food_logged_at", "food_logs", "logged_at")
}
+// weight_logs was the one day-scoped table left without this pass, which is exactly
+// where an unrepaired non-UTC value could sit and stall the day backfill.
+func normalizeWeightLoggedAt() {
+ normalizeUTCTimestamps("normalize_weight_logged_at", "weight_logs", "logged_at")
+}
+
// normalizeUTCTimestamps rewrites any table.column value stored with a non-UTC zone
// offset to its UTC equivalent. Normalizing also repairs reads: a fixed-offset zone
// with no name is stored as its offset twice ('… +0800 +0800'), which the driver
@@ -761,5 +800,3 @@ CREATE TABLE IF NOT EXISTS program_sets (
target_weight REAL NOT NULL DEFAULT 0
);
`
-
-
diff --git a/backend/db/migrations_test.go b/backend/db/migrations_test.go
index 9bb0386..08410ad 100644
--- a/backend/db/migrations_test.go
+++ b/backend/db/migrations_test.go
@@ -489,3 +489,68 @@ func TestBackfillLocalDays_isIdempotent(t *testing.T) {
t.Errorf("second migration pass rewrote a filled day to %q", day)
}
}
+
+// One unreadable legacy timestamp must not take the rest of the upgrade with it.
+//
+// backfillDayColumn used to scan straight into time.Time, so a value the driver cannot
+// parse failed the scan, returned an error, and made backfillLocalDays bail — before
+// the workout-offset backfill and before the completion flag. Every later boot retried
+// and failed identically, leaving logged_on unset and tz_offset_minutes null forever.
+// A row that cannot be read is now skipped and reported; everything else still lands.
+func TestBackfillLocalDays_oneUnreadableRowDoesNotBlockTheRest(t *testing.T) {
+ setupMigrationTestDB(t)
+
+ if _, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('old@user', 'x')`); err != nil {
+ t.Fatalf("seed user: %v", err)
+ }
+ if _, err := DB.Exec(`INSERT INTO user_settings (user_id, timezone) VALUES (1, 'America/New_York')`); err != nil {
+ t.Fatalf("seed settings: %v", err)
+ }
+
+ good := time.Date(2026, 8, 5, 16, 0, 0, 0, time.UTC)
+ // Written as raw text the driver cannot turn back into a time.Time — the shape
+ // normalizeUTCTimestamps exists to repair, which is why it now covers weight_logs.
+ if _, err := DB.Exec(`INSERT INTO weight_logs (user_id, weight, logged_at) VALUES (1, 180, 'not-a-timestamp')`); err != nil {
+ t.Fatalf("seed unreadable weight: %v", err)
+ }
+ if _, err := DB.Exec(`INSERT INTO weight_logs (user_id, weight, logged_at) VALUES (1, 181, ?)`, good); err != nil {
+ t.Fatalf("seed good weight: %v", err)
+ }
+ if _, err := DB.Exec(`INSERT INTO workouts (user_id, name, started_at) VALUES (1, 'lift', ?)`, good); err != nil {
+ t.Fatalf("seed workout: %v", err)
+ }
+ // The offset backfill reads started_at the same way, and had the same defect. Seeding
+ // an unreadable weight row alone let that one survive a review: the run died in the
+ // weight pass, so the workout pass never got to fail on its own account.
+ if _, err := DB.Exec(`INSERT INTO workouts (user_id, name, started_at) VALUES (1, 'bad lift', 'not-a-timestamp')`); err != nil {
+ t.Fatalf("seed unreadable workout: %v", err)
+ }
+
+ alterMigrations()
+
+ var day string
+ if err := DB.QueryRow(`SELECT logged_on FROM weight_logs WHERE weight = 181`).Scan(&day); err != nil {
+ t.Fatalf("read good weight day: %v", err)
+ }
+ if want := "2026-08-05"; day != want {
+ t.Errorf("readable row was not backfilled: got %q, want %q", day, want)
+ }
+
+ // The offset backfill runs after the day backfill, so it is the first casualty of
+ // an early return and the clearest signal the run completed.
+ var offset sql.NullInt64
+ if err := DB.QueryRow(`SELECT tz_offset_minutes FROM workouts WHERE name = 'lift'`).Scan(&offset); err != nil {
+ t.Fatalf("read workout offset: %v", err)
+ }
+ if !offset.Valid {
+ t.Error("workout offset never backfilled — the run stopped at the unreadable row")
+ }
+
+ done, err := hasMigrationFlag("backfill_local_days")
+ if err != nil {
+ t.Fatalf("check flag: %v", err)
+ }
+ if !done {
+ t.Error("completion flag never set — every boot will retry this forever")
+ }
+}
diff --git a/backend/stores/food.go b/backend/stores/food.go
index e75a7a7..5a4868e 100644
--- a/backend/stores/food.go
+++ b/backend/stores/food.go
@@ -11,6 +11,15 @@ type FoodStore struct{ db *sql.DB }
func NewFoodStore(db *sql.DB) *FoodStore { return &FoodStore{db: db} }
+// foodDay is the day a row is filed under — same rule and same reason as weightDay:
+// logged_on defaults to ” and the backfill leaves it unset for a row whose stored
+// instant is unreadable, which would otherwise drop that entry out of its own diary
+// day and out of every history bucket.
+const foodDay = `CASE
+ WHEN logged_on <> '' THEN logged_on
+ WHEN logged_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*' THEN substr(logged_at, 1, 10)
+ END`
+
const foodLogSelect = `SELECT id, user_id, name, meal, calories, protein, carbs, fat, fiber, servings, serving_size, barcode, image_url, logged_at, logged_on, created_at FROM food_logs`
func scanFoodLog(row interface{ Scan(...any) error }, f *models.FoodLog) error {
@@ -29,7 +38,7 @@ func scanFoodLog(row interface{ Scan(...any) error }, f *models.FoodLog) error {
// instant so entries still read in the order they happened within the day.
func (s *FoodStore) ListByDay(uid int64, day string) ([]models.FoodLog, error) {
rows, err := s.db.Query(
- foodLogSelect+` WHERE user_id = ? AND logged_on = ? ORDER BY logged_at ASC, id ASC`,
+ foodLogSelect+` WHERE user_id = ? AND `+foodDay+` = ? ORDER BY logged_at ASC, id ASC`,
uid, day,
)
if err != nil {
@@ -47,7 +56,6 @@ func (s *FoodStore) ListByDay(uid int64, day string) ([]models.FoodLog, error) {
return logs, rows.Err()
}
-
// Get returns one user-owned food log, or sql.ErrNoRows.
func (s *FoodStore) Get(uid, id int64) (models.FoodLog, error) {
var f models.FoodLog
@@ -106,13 +114,12 @@ func (s *FoodStore) DailyMacros(uid int64, day string) (models.DailyStats, error
err := s.db.QueryRow(
`SELECT COALESCE(SUM(calories),0), COALESCE(SUM(protein),0),
COALESCE(SUM(carbs),0), COALESCE(SUM(fat),0), COALESCE(SUM(fiber),0)
- FROM food_logs WHERE user_id = ? AND logged_on = ?`,
+ FROM food_logs WHERE user_id = ? AND `+foodDay+` = ?`,
uid, day,
).Scan(&stats.TotalCalories, &stats.TotalProtein, &stats.TotalCarbs, &stats.TotalFat, &stats.TotalFiber)
return stats, err
}
-
// History returns per-day macro totals from sinceDay (YYYY-MM-DD) onward.
//
// Grouped in SQL now that the day is a stored column. The previous version read every
@@ -122,13 +129,13 @@ func (s *FoodStore) DailyMacros(uid int64, day string) (models.DailyStats, error
// cannot disagree about which day an entry belongs to.
func (s *FoodStore) History(uid int64, sinceDay string) ([]models.FoodHistoryPoint, error) {
rows, err := s.db.Query(
- `SELECT logged_on,
+ `SELECT `+foodDay+` AS day,
COALESCE(SUM(calories),0), COALESCE(SUM(protein),0),
COALESCE(SUM(carbs),0), COALESCE(SUM(fat),0)
FROM food_logs
- WHERE user_id = ? AND logged_on >= ?
- GROUP BY logged_on
- ORDER BY logged_on ASC`,
+ WHERE user_id = ? AND `+foodDay+` >= ?
+ GROUP BY day
+ ORDER BY day ASC`,
uid, sinceDay,
)
if err != nil {
diff --git a/backend/stores/weight.go b/backend/stores/weight.go
index bd27e61..00a6976 100644
--- a/backend/stores/weight.go
+++ b/backend/stores/weight.go
@@ -30,23 +30,47 @@ type WeightStats struct {
const weightCols = `id, user_id, weight, notes, logged_at, logged_on, created_at`
+// weightDay is the day a row is filed under, for every query that filters, groups or
+// orders by day. NULL when the row has neither — see below for why that matters.
+//
+// logged_on defaults to ” and the backfill leaves a row unset when its stored instant
+// is unreadable. Read raw, ” sorts before every real date, so an unset row becomes the
+// reported *starting* weight and skews change_30d; and `logged_on >= ?` excludes it, so
+// the same row silently vanishes from every windowed query and chart. Falling back to
+// the instant's own date keeps such a row in roughly the right place instead of at both
+// extremes at once. The fallback reads the UTC day, which is the best available answer
+// for a row whose zone could not be established.
+//
+// It yields NULL rather than a substring when logged_at is not a date, because the only
+// rows that reach the fallback are the ones the backfill could not read — so slicing
+// them returns text like 'not-a-tim', and in SQLite's collation that sorts AFTER every
+// real date. It would become the permanent "latest" weight and leak to clients as a
+// history point's date. NULL keeps an unreadable row out of the answer instead of
+// putting it first.
+const weightDay = `CASE
+ WHEN logged_on <> '' THEN logged_on
+ WHEN logged_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*' THEN substr(logged_at, 1, 10)
+ END`
+
func (s *WeightStore) List(uid int64, f WeightFilter) ([]models.WeightLog, error) {
q := `SELECT ` + weightCols + ` FROM weight_logs WHERE user_id = ?`
args := []any{uid}
if f.FromDay != nil {
- q += ` AND logged_on >= ?`
+ q += ` AND ` + weightDay + ` >= ?`
args = append(args, *f.FromDay)
}
if f.ToDay != nil {
// Inclusive: the caller asked for a day, not an exclusive bound.
- q += ` AND logged_on <= ?`
+ q += ` AND ` + weightDay + ` <= ?`
args = append(args, *f.ToDay)
}
// Newest day first, and only then newest instant within it. Every reader labels a
// row with logged_on, so ordering by the instant alone puts the list out of the order
// it appears to be in: an entry filed for the 10th from UTC+14 is an earlier *moment*
// than one filed for the 9th from UTC-11, and sorted by instant it renders below it.
- q += ` ORDER BY logged_on DESC, logged_at DESC, id DESC LIMIT ? OFFSET ?`
+ // SQLite sorts NULL below every value, so DESC already puts an undated row last —
+ // no explicit NULL handling, and the day term can be served by an index.
+ q += ` ORDER BY ` + weightDay + ` DESC, logged_at DESC, id DESC LIMIT ? OFFSET ?`
args = append(args, f.Limit, f.Offset)
rows, err := s.db.Query(q, args...)
@@ -95,7 +119,7 @@ func (s *WeightStore) UpsertForDay(uid int64, req models.LogWeightRequest, day s
id, err := inTx(s.db, func(tx *sql.Tx) (int64, error) {
var id int64
err := tx.QueryRow(
- `SELECT id FROM weight_logs WHERE user_id = ? AND logged_on = ? ORDER BY id DESC LIMIT 1`,
+ `SELECT id FROM weight_logs WHERE user_id = ? AND `+weightDay+` = ? ORDER BY id DESC LIMIT 1`,
uid, day,
).Scan(&id)
switch err {
@@ -144,7 +168,7 @@ func (s *WeightStore) Update(uid, id int64, req models.LogWeightRequest, day str
// Same day as the upsert keys on — one entry per the *user's* day. Runs after
// the update above, so it matches the row's new day, not the one it left.
_, err = tx.Exec(
- `DELETE FROM weight_logs WHERE user_id = ? AND id != ? AND logged_on = ?`,
+ `DELETE FROM weight_logs WHERE user_id = ? AND id != ? AND `+weightDay+` = ?`,
uid, id, day,
)
return err
@@ -170,11 +194,11 @@ func (s *WeightStore) Stats(uid int64, since7d, since30d string) (WeightStats, e
var latest, oldest, minW, maxW, avgW sql.NullFloat64
var count int
err := s.db.QueryRow(
+ // "Latest" means the most recent day weighed, not the most recent instant: those
+ // part company once a row's day comes from logged_on. Same ordering as List.
`SELECT
- -- "Latest" means the most recent day weighed, not the most recent instant: those
- -- part company once a row's day comes from logged_on. Same ordering as List.
- (SELECT weight FROM weight_logs WHERE user_id = ? ORDER BY logged_on DESC, logged_at DESC, id DESC LIMIT 1),
- (SELECT weight FROM weight_logs WHERE user_id = ? ORDER BY logged_on ASC, logged_at ASC, id ASC LIMIT 1),
+ (SELECT weight FROM weight_logs WHERE user_id = ? AND (`+weightDay+`) IS NOT NULL ORDER BY `+weightDay+` DESC, logged_at DESC, id DESC LIMIT 1),
+ (SELECT weight FROM weight_logs WHERE user_id = ? AND (`+weightDay+`) IS NOT NULL ORDER BY `+weightDay+` ASC, logged_at ASC, id ASC LIMIT 1),
MIN(weight), MAX(weight), AVG(weight), COUNT(*)
FROM weight_logs WHERE user_id = ?`,
uid, uid, uid,
@@ -206,8 +230,8 @@ func (s *WeightStore) changeOver(uid int64, sinceDay string) (float64, error) {
var latest, earliest sql.NullFloat64
if err := s.db.QueryRow(
`SELECT
- (SELECT weight FROM weight_logs WHERE user_id = ? AND logged_on >= ? ORDER BY logged_on DESC, logged_at DESC, id DESC LIMIT 1),
- (SELECT weight FROM weight_logs WHERE user_id = ? AND logged_on >= ? ORDER BY logged_on ASC, logged_at ASC, id ASC LIMIT 1)`,
+ (SELECT weight FROM weight_logs WHERE user_id = ? AND `+weightDay+` >= ? ORDER BY `+weightDay+` DESC, logged_at DESC, id DESC LIMIT 1),
+ (SELECT weight FROM weight_logs WHERE user_id = ? AND `+weightDay+` >= ? ORDER BY `+weightDay+` ASC, logged_at ASC, id ASC LIMIT 1)`,
uid, sinceDay, uid, sinceDay,
).Scan(&latest, &earliest); err != nil {
return 0, err
diff --git a/docs/API_CHANGES.md b/docs/API_CHANGES.md
new file mode 100644
index 0000000..04a4cbd
--- /dev/null
+++ b/docs/API_CHANGES.md
@@ -0,0 +1,24 @@
+# API changes
+
+Breaking changes to the HTTP API, recorded when they land so the next release's notes
+can carry them. Self-hosters and anyone driving the API directly are the audience — the
+first-party clients are updated in the same PR and never notice.
+
+Newest first. Delete an entry once it has shipped in a release whose notes mention it.
+
+## `GET /api/v1/weight` — `from` / `to` accept a calendar day only
+
+Both bounds must now be `YYYY-MM-DD`, and anything else is rejected with `400`.
+
+Previously the endpoint accepted either a bare day or a full RFC3339 timestamp, and a
+malformed bound was ignored rather than refused — so a typo silently returned the whole
+history instead of the window that was asked for.
+
+The two modes answered the same question through different columns: the day mode filters
+on the day a row is filed under, the timestamp mode filtered on the instant. Those agree
+until a user changes timezone, which is exactly when a range query matters. No in-tree
+client ever sent the timestamp form.
+
+A third-party caller sending `from=2026-04-25T12:00:00Z` gets a `400` and should send
+`from=2026-04-25`. Ignoring a bad bound was itself a bug — answering a narrow question
+with the entire history reads as data loss in reverse — so the rejection is deliberate.
diff --git a/mobile/.maestro/assert-day-after-travel.yaml b/mobile/.maestro/assert-day-after-travel.yaml
deleted file mode 100644
index ffa9948..0000000
--- a/mobile/.maestro/assert-day-after-travel.yaml
+++ /dev/null
@@ -1,33 +0,0 @@
-# The point of the whole feature, on a real device: an entry keeps the day it was
-# filed under after the phone changes timezone.
-#
-# The runner flips the emulator's zone between log-weight.yaml and this flow, so the
-# app relaunches somewhere else entirely. EXPECTED_DAY is the day the entry was
-# written under, passed in by the runner; UNEXPECTED_DAY is the day it would drift to
-# if a screen went back to deriving the label from the device.
-#
-# Asserting both directions matters. EXPECTED_DAY alone passes on a list that renders
-# *both* days, which is exactly what a partial fix looks like — the history row
-# corrected while the chart or the detail header still reads the instant.
-#
-# This caught a real regression: with the device moved NY -> Tokyo, a row stored as
-# logged_on 2026-08-09 rendered "Aug 10, 2026", because the row formatted logged_at
-# (the instant) instead of the stored day.
-appId: local.lyftr.app
-env:
- EXPECTED_DAY: ""
- UNEXPECTED_DAY: ""
----
-- runFlow: login.yaml
-
-- tapOn:
- text: "Weight"
- index: 0
-- assertVisible: "Track your body weight over time"
-
-- scrollUntilVisible:
- element: "HISTORY"
- direction: DOWN
-
-- assertVisible: ${EXPECTED_DAY}
-- assertNotVisible: ${UNEXPECTED_DAY}
diff --git a/mobile/.maestro/day-labels.yaml b/mobile/.maestro/day-labels.yaml
deleted file mode 100644
index 12c4b0c..0000000
--- a/mobile/.maestro/day-labels.yaml
+++ /dev/null
@@ -1,34 +0,0 @@
-# Every screen that names a day must name the day the row was filed under.
-#
-# The dashboard header is the one place the *device* zone is still the right answer
-# ("what is today"). Everything below it reads a stored value: diary rows carry
-# logged_on, workouts carry tz_offset_minutes. If a screen ever goes back to deriving
-# a day from the device, this fails on the screen that regressed.
-appId: local.lyftr.app
----
-- runFlow: login.yaml
-
-# "What is today" — device zone, formatted like the dashboard header ("SUNDAY, AUGUST 9").
-- evalScript: |
- ${output.todayHeader = new Date()
- .toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })
- .toUpperCase()}
-- assertVisible: ${output.todayHeader}
-
-# Workout rows render their day from the offset recorded when the workout started,
-# never from where the phone is now.
-- tapOn:
- text: "Workouts"
- index: 0
-- assertVisible: "Track and review your training sessions"
-- assertVisible: "[A-Z][a-z]{2} \\d{1,2}, \\d{4}"
-
-# Weight rows render logged_on verbatim.
-- tapOn:
- text: "Weight"
- index: 0
-- assertVisible: "Track your body weight over time"
-- scrollUntilVisible:
- element: "History"
- direction: DOWN
-- assertVisible: "[A-Z][a-z]{2} \\d{1,2}, \\d{4}"
diff --git a/mobile/.maestro/log-weight.yaml b/mobile/.maestro/log-weight.yaml
deleted file mode 100644
index a49fa01..0000000
--- a/mobile/.maestro/log-weight.yaml
+++ /dev/null
@@ -1,40 +0,0 @@
-# Logs a weight and asserts it lands on the device's today.
-#
-# The weight value is left at its prefilled default — the day is what is under test,
-# not the number.
-#
-# The screen guards against a second entry on a day that already has one ("Already
-# logged on ... Log again anyway?"). That guard is a feature, but it means a bare
-# tapOn "Log Weight" can succeed as a *tap* while submitting nothing — which is how an
-# earlier version of this flow passed 13/13 without writing a row. Waving the guard
-# through keeps the flow honest on a day that already has an entry.
-appId: local.lyftr.app
----
-- runFlow: login.yaml
-
-- tapOn:
- text: "Weight"
- index: 0
-- assertVisible: "Track your body weight over time"
-
-# "Log Weight" appears twice on this screen — the card heading and the submit button.
-# index 1 is the button; index 0 would tap the heading and silently do nothing.
-- tapOn:
- text: "Log Weight"
- index: 1
-
-- runFlow:
- when:
- visible: "Log Anyway"
- commands:
- - tapOn: "Log Anyway"
-
-- evalScript: |
- ${output.day = new Date()
- .toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
-
-# The row the app just wrote must be filed under the device's today.
-- scrollUntilVisible:
- element: "HISTORY"
- direction: DOWN
-- assertVisible: ${output.day}
diff --git a/mobile/.maestro/login.yaml b/mobile/.maestro/login.yaml
deleted file mode 100644
index 2c173e7..0000000
--- a/mobile/.maestro/login.yaml
+++ /dev/null
@@ -1,43 +0,0 @@
-# Reusable sign-in. Points the app at the dev backend and logs in as the demo user.
-#
-# 10.0.2.2 is the Android emulator's alias for the host machine's loopback — the
-# emulator has its own 127.0.0.1, so "localhost:3000" would resolve to the emulator
-# itself and fail. On a physical device over Tailscale, pass SERVER_URL instead:
-# maestro test -e SERVER_URL=http://100.x.y.z:3000 .maestro/login.yaml
-#
-# Selectors are text, because the app has no testIDs — mobile/CONVENTIONS.md puts
-# accessibilityLabel in their place, and Maestro matches those too.
-appId: local.lyftr.app
-env:
- SERVER_URL: http://10.0.2.2:3000
- PASSWORD: password123
----
-- launchApp:
- clearState: true
- permissions:
- all: deny
-
-- assertVisible: "Welcome back"
-
-# The URL field is collapsed behind a summary row until the row is tapped.
-- tapOn: "Server settings"
-- tapOn: "https://your-server.example.com"
-- inputText: ${SERVER_URL}
-- hideKeyboard
-- tapOn: "Test & save"
-# Proves the app reached *our* backend, not just that a field was filled.
-- assertVisible: "Connected to.*"
-
-- tapOn: "[email protected]"
-- inputText: ${EMAIL}
-# The soft keyboard covers the lower half of the form, so "below PASSWORD" resolves
-# to nothing until it is dismissed.
-- hideKeyboard
-- tapOn:
- below: "PASSWORD"
-- inputText: ${PASSWORD}
-- hideKeyboard
-- tapOn: "Sign in"
-
-- assertVisible: "Good (morning|afternoon|evening), demo"
diff --git a/mobile/.maestro/run-travel-suite.sh b/mobile/.maestro/run-travel-suite.sh
deleted file mode 100644
index 2cafd6d..0000000
--- a/mobile/.maestro/run-travel-suite.sh
+++ /dev/null
@@ -1,45 +0,0 @@
-#!/usr/bin/env bash
-# Runs the day-attribution suite across a timezone change on a real Android runtime.
-#
-# Maestro cannot change a device's timezone, so this wraps it: log an entry in one
-# zone, move the device, assert the entry did not move with it. The hop is 13 hours
-# (New York -> Tokyo), deliberately past 12 — under 12 the old device-derived label
-# happened to survive for entries written near midday, which is why the bug hid for
-# so long.
-#
-# Usage: mobile/.maestro/run-travel-suite.sh [avd-serial]
-set -euo pipefail
-
-SERIAL="${1:-emulator-5554}"
-ADB="${ANDROID_HOME:-$LOCALAPPDATA/Android/Sdk}/platform-tools/adb"
-FLOWS="$(cd "$(dirname "$0")" && pwd)"
-
-set_tz() {
- echo "── device timezone -> $1"
- "$ADB" -s "$SERIAL" shell service call alarm 3 s16 "$1" >/dev/null
- sleep 2
-}
-
-current_day() {
- # The device's own idea of today, formatted the way the app renders a row.
- "$ADB" -s "$SERIAL" shell date +%Y-%m-%d | tr -d '\r'
-}
-
-restore() { set_tz "America/New_York"; }
-trap restore EXIT
-
-set_tz "America/New_York"
-DAY_BEFORE="$(current_day)"
-echo "── device day before travel: $DAY_BEFORE"
-
-maestro test "$FLOWS/day-labels.yaml"
-maestro test "$FLOWS/log-weight.yaml"
-
-# Reformat to the app's display form: "Aug 9, 2026".
-EXPECTED_DAY="$(date -d "$DAY_BEFORE" '+%b %-d, %Y' 2>/dev/null || date -j -f %Y-%m-%d "$DAY_BEFORE" '+%b %-d, %Y')"
-echo "── expecting the entry to stay on: $EXPECTED_DAY"
-
-set_tz "Asia/Tokyo"
-maestro test -e EXPECTED_DAY="$EXPECTED_DAY" "$FLOWS/assert-day-after-travel.yaml"
-
-echo "── entry held its day across a 13-hour move"
diff --git a/mobile/app/(tabs)/index.tsx b/mobile/app/(tabs)/index.tsx
index 828bad3..336a743 100644
--- a/mobile/app/(tabs)/index.tsx
+++ b/mobile/app/(tabs)/index.tsx
@@ -9,7 +9,7 @@ import {
import {
Activity, AlertCircle, ArrowRight, BookOpen, ChevronRight, Dumbbell, Play, Plus, Scale, Timer, TrendingUp,
} from 'lucide-react-native'
-import { activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, isDayStartable, sessionNameForDay, todaysDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout, workoutDay, entryDay } from '@lyftr/shared'
+import { activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, isDayStartable, sessionNameForDay, todaysDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout, workoutDay, entryDay, dayToLocalDate} from '@lyftr/shared'
import { AppText, Card, IconButton, Label, Screen, SectionHeader, SegmentedControl } from '../../src/components/ui'
import { ExerciseImage } from '../../src/components/workouts/ExerciseImage'
import {
@@ -225,7 +225,7 @@ export default function Dashboard() {
}
const chartData = workouts.slice(0, Number(volumePeriod)).reverse().map((w) => ({
- date: format(new Date(workoutDay(w) + 'T12:00:00'), 'M/d'),
+ date: format(dayToLocalDate(workoutDay(w)), 'M/d'),
volume: displayVolume(calcVolume(w), unit),
name: w.name,
}))
@@ -279,7 +279,7 @@ export default function Dashboard() {
const fatPct = Math.min(100, (food.total_fat / settings.fat_target) * 100) || 0
const sparkData = [...weightLogs].reverse().map((l) => ({
- date: format(new Date(entryDay(l) + 'T12:00:00'), 'M/d'),
+ date: format(dayToLocalDate(entryDay(l)), 'M/d'),
weight: displayWeight(l.weight, unit),
}))
@@ -522,7 +522,7 @@ export default function Dashboard() {
<Label className="mb-1">Last workout</Label>
<Text className="font-sans-semibold text-base text-tx-primary" numberOfLines={1}>{lastWorkout.name}</Text>
<AppText variant="caption" color="muted" className="mt-0.5">
- {format(new Date(workoutDay(lastWorkout) + 'T12:00:00'), 'MMM d')}
+ {format(dayToLocalDate(workoutDay(lastWorkout)), 'MMM d')}
{mins > 0 ? ` · ${mins} min` : ''}
{totalSets > 0 ? ` · ${totalSets} sets` : ''}
{totalVolume > 0 ? ` · ${totalVolume.toLocaleString()} ${wUnit}` : ''}
diff --git a/mobile/app/(tabs)/nutrition/[id].tsx b/mobile/app/(tabs)/nutrition/[id].tsx
index 28a86e9..9af8be9 100644
--- a/mobile/app/(tabs)/nutrition/[id].tsx
+++ b/mobile/app/(tabs)/nutrition/[id].tsx
@@ -3,7 +3,7 @@ import { Image, Pressable, ScrollView, Text, View } from 'react-native'
import { router, useLocalSearchParams } from 'expo-router'
import { format } from 'date-fns'
import { AlertCircle, ArrowLeft, Edit2, Flame, Trash2 } from 'lucide-react-native'
-import { entryDay, type FoodLog } from '@lyftr/shared'
+import { entryDay, type FoodLog, dayToLocalDate} from '@lyftr/shared'
import {
AppText, Card, ConfirmSheet, Loading, Screen, deleteConfirmProps,
} from '../../../src/components/ui'
@@ -87,7 +87,7 @@ export default function NutritionDetail() {
...(entry.serving_size ? [{ label: 'Serving size', value: entry.serving_size }] : []),
{ label: 'Servings', value: String(entry.servings), tabular: true },
{ label: 'Meal', value: MEAL_LABELS[meal] },
- { label: 'Logged', value: format(new Date(entryDay(entry) + 'T12:00:00'), 'EEE, MMM d, yyyy') },
+ { label: 'Logged', value: format(dayToLocalDate(entryDay(entry)), 'EEE, MMM d, yyyy') },
]
return (
diff --git a/mobile/app/(tabs)/nutrition/index.tsx b/mobile/app/(tabs)/nutrition/index.tsx
index cc16cc8..6a8490f 100644
--- a/mobile/app/(tabs)/nutrition/index.tsx
+++ b/mobile/app/(tabs)/nutrition/index.tsx
@@ -6,7 +6,7 @@ import { format, subDays, addDays } from 'date-fns'
import {
AlertCircle, CalendarDays, CheckCircle2, ChevronLeft, ChevronRight, Flame, Plus, Utensils,
} from 'lucide-react-native'
-import { todayStr, type DailyStats, type FoodLog } from '@lyftr/shared'
+import { todayStr, type DailyStats, type FoodLog, dayToLocalDate} from '@lyftr/shared'
import {
AppText, Card, DateInput, IconButton, Label, PageHeader, Screen, SearchField, SectionHeader, SegmentedControl, Toast,
} from '../../../src/components/ui'
@@ -181,7 +181,7 @@ export default function Nutrition() {
const chartW = chartWidth || Math.max(0, windowWidth - 72)
const isToday = selectedDate === todayStr()
- const selectedDateObj = new Date(selectedDate + 'T12:00:00')
+ const selectedDateObj = dayToLocalDate(selectedDate)
const prevDate = format(subDays(selectedDateObj, 1), 'yyyy-MM-dd')
const nextDate = format(addDays(selectedDateObj, 1), 'yyyy-MM-dd')
const canGoNext = selectedDate < todayStr()
diff --git a/mobile/app/(tabs)/weight/[id].tsx b/mobile/app/(tabs)/weight/[id].tsx
index 73c18b5..a1e5ac7 100644
--- a/mobile/app/(tabs)/weight/[id].tsx
+++ b/mobile/app/(tabs)/weight/[id].tsx
@@ -4,7 +4,7 @@ import { router, useLocalSearchParams } from 'expo-router'
import { format } from 'date-fns'
import * as Haptics from 'expo-haptics'
import { AlertCircle, ArrowLeft, Edit2, Scale, Trash2 } from 'lucide-react-native'
-import { apiErrorMessage, dayToInstant, displayWeight, maxWeight, resolveWeightLbs, weightError, weightShort, type WeightLog, entryDay } from '@lyftr/shared'
+import { apiErrorMessage, dayToInstant, displayWeight, maxWeight, resolveWeightLbs, weightError, weightShort, type WeightLog, entryDay, dayToLocalDate} from '@lyftr/shared'
import {
AppText, Button, Card, ConfirmSheet, DateInput, Field, Label, Loading, NumberField,
NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, Screen, StepperTile, deleteConfirmProps,
@@ -174,7 +174,7 @@ export default function WeightDetail() {
<AppText variant="body" color="muted" className="mb-1.5">{wUnit}</AppText>
</View>
<AppText variant="body" color="muted" className="mt-1">
- {format(new Date(entryDay(log) + 'T12:00:00'), 'EEEE, MMMM d, yyyy')}
+ {format(dayToLocalDate(entryDay(log)), 'EEEE, MMMM d, yyyy')}
</AppText>
{log.notes ? (
<AppText variant="body" color="secondary" className="mt-2 italic">"{log.notes}"</AppText>
@@ -241,7 +241,7 @@ export default function WeightDetail() {
<ConfirmSheet
{...deleteConfirmProps({
title: 'Delete Entry?',
- subject: `${format(new Date(entryDay(log) + 'T12:00:00'), 'MMMM d, yyyy')} · ${displayWeight(log.weight, unit)} ${wUnit}`,
+ subject: `${format(dayToLocalDate(entryDay(log)), 'MMMM d, yyyy')} · ${displayWeight(log.weight, unit)} ${wUnit}`,
})}
open={confirming}
busy={deleting}
diff --git a/mobile/app/(tabs)/weight/index.tsx b/mobile/app/(tabs)/weight/index.tsx
index 0bae67f..4932946 100644
--- a/mobile/app/(tabs)/weight/index.tsx
+++ b/mobile/app/(tabs)/weight/index.tsx
@@ -7,7 +7,7 @@ import {
Activity, AlertCircle, ArrowDown, ArrowUp, Calendar, Minus, Scale, Sunrise,
TrendingDown, TrendingUp, X,
} from 'lucide-react-native'
-import { apiErrorMessage, dayToInstant, daysAgoStr, displayToLbs, displayWeight, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay } from '@lyftr/shared'
+import { apiErrorMessage, dayToInstant, daysAgoStr, displayToLbs, displayWeight, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay, dayToLocalDate} from '@lyftr/shared'
import {
AppText, Button, Card, DateInput, Field, Label, NumberField, NumericKeyboardAccessory,
NUMERIC_ACCESSORY_ID, PageHeader, Screen, SegmentedControl, StepperTile,
@@ -106,7 +106,7 @@ export default function Weight() {
const chartData: ChartPoint[] = useMemo(
() =>
[...chartLogs].reverse().map((l) => {
- const d = new Date(entryDay(l) + 'T12:00:00')
+ const d = dayToLocalDate(entryDay(l))
return { date: format(d, 'M/d'), weight: displayWeight(l.weight, unit), sub: format(d, 'MMM d, yyyy') }
}),
[chartLogs, unit]
@@ -291,7 +291,7 @@ export default function Weight() {
<AlertCircle size={16} color={brand.warningSoft} style={{ marginTop: 2 }} />
<View className="min-w-0 flex-1">
<Text className="font-sans-semibold text-sm text-warning-400">
- Already logged on {format(new Date(entryDay(items[0]) + 'T12:00:00'), 'MMM d')} ({displayWeight(items[0].weight, unit)} {wUnit}). Log again anyway?
+ Already logged on {format(dayToLocalDate(entryDay(items[0])), 'MMM d')} ({displayWeight(items[0].weight, unit)} {wUnit}). Log again anyway?
</Text>
<View className="mt-2 flex-row gap-2">
<Pressable
diff --git a/mobile/app/(tabs)/workouts/[id].tsx b/mobile/app/(tabs)/workouts/[id].tsx
index ad8394f..533a590 100644
--- a/mobile/app/(tabs)/workouts/[id].tsx
+++ b/mobile/app/(tabs)/workouts/[id].tsx
@@ -5,7 +5,7 @@ import { format } from 'date-fns'
import {
AlertCircle, ArrowLeft, ChevronRight, Clock, Edit2, Layers, Pause, TimerOff, Trash2, TrendingUp,
} from 'lucide-react-native'
-import { apiErrorMessage, displayVolume, displayWeight, weightShort, type Workout, type Set as WorkoutSet, workoutDay } from '@lyftr/shared'
+import { apiErrorMessage, displayVolume, displayWeight, weightShort, type Workout, type Set as WorkoutSet, workoutDay, dayToLocalDate} from '@lyftr/shared'
import { AppText, ConfirmSheet, Loading, Screen, deleteConfirmProps } from '../../../src/components/ui'
import { ExerciseImage } from '../../../src/components/workouts/ExerciseImage'
import { client, useSettingsStore } from '../../../src/lib/lyftr'
@@ -185,7 +185,7 @@ export default function WorkoutDetail() {
<View className="flex-1">
<AppText variant="heading">{workout.name}</AppText>
<AppText variant="body" color="muted" className="mt-0.5">
- {format(new Date(workoutDay(workout) + 'T12:00:00'), 'EEEE, MMMM d, yyyy')}
+ {format(dayToLocalDate(workoutDay(workout)), 'EEEE, MMMM d, yyyy')}
</AppText>
</View>
</View>
diff --git a/mobile/src/components/nutrition/NutritionCharts.tsx b/mobile/src/components/nutrition/NutritionCharts.tsx
index e72957b..b0032b0 100644
--- a/mobile/src/components/nutrition/NutritionCharts.tsx
+++ b/mobile/src/components/nutrition/NutritionCharts.tsx
@@ -3,6 +3,7 @@ import { View } from 'react-native'
import * as Haptics from 'expo-haptics'
import Svg, { Circle, G, Line, Path, Rect, Text as SvgText } from 'react-native-svg'
import { format } from 'date-fns'
+import { dayToLocalDate } from '@lyftr/shared'
import { AppText } from '../ui'
import { useTheme } from '../../theme/useTheme'
import { MACRO_COLORS } from './nutritionMeta'
@@ -114,7 +115,7 @@ export function MacroHistoryChart({ data, width, height = 200 }: {
// Thin x-labels so they never overlap (recharts auto-skips too).
const maxLabels = Math.max(2, Math.floor(plotW / 44))
const every = Math.ceil(n / maxLabels)
- const fmt = (d: string) => format(new Date(d + 'T12:00:00'), 'M/d')
+ const fmt = (d: string) => format(dayToLocalDate(d), 'M/d')
const selPt = sel != null ? data[sel] : null
@@ -166,7 +167,7 @@ export function MacroHistoryChart({ data, width, height = 200 }: {
className="absolute rounded-lg border border-surface-border bg-surface-raised px-2.5 py-1.5"
style={{ left: clamp(xAt(sel!) - 60, 0, Math.max(0, width - 120)), top: 0, width: 120 }}
>
- <AppText variant="caption" color="muted">{format(new Date(selPt.date + 'T12:00:00'), 'MMM d')}</AppText>
+ <AppText variant="caption" color="muted">{format(dayToLocalDate(selPt.date), 'MMM d')}</AppText>
<View className="mt-0.5 gap-0.5">
{[
{ label: 'Protein', value: selPt.protein, color: MACRO_COLORS.protein },
diff --git a/mobile/src/components/weight/WeightEntryRow.tsx b/mobile/src/components/weight/WeightEntryRow.tsx
index 9293c7f..893ac02 100644
--- a/mobile/src/components/weight/WeightEntryRow.tsx
+++ b/mobile/src/components/weight/WeightEntryRow.tsx
@@ -4,7 +4,7 @@ import { router } from 'expo-router'
import { format } from 'date-fns'
import * as Haptics from 'expo-haptics'
import { ChevronRight, MoreVertical, Scale, TrendingDown, TrendingUp } from 'lucide-react-native'
-import { displayWeight, entryDay, weightShort, type WeightLog } from '@lyftr/shared'
+import { displayWeight, entryDay, weightShort, type WeightLog, dayToLocalDate} from '@lyftr/shared'
import { ActionSheet, AppText, Card, ConfirmSheet, IconButton, deleteAction, deleteConfirmProps, editAction } from '../ui'
import { useTheme } from '../../theme/useTheme'
import { client } from '../../lib/lyftr'
@@ -32,7 +32,7 @@ export function WeightEntryRow({ item, next, unit, onDeleted }: Props) {
const deltaLbs = next ? item.weight - next.weight : 0
const displayW = displayWeight(item.weight, unit)
const displayDelta = displayWeight(Math.abs(deltaLbs), unit)
- const dateLabel = format(new Date(entryDay(item) + 'T12:00:00'), 'MMM d, yyyy')
+ const dateLabel = format(dayToLocalDate(entryDay(item)), 'MMM d, yyyy')
const handleDelete = async () => {
setDeleting(true)
diff --git a/mobile/src/components/workouts/WorkoutCard.tsx b/mobile/src/components/workouts/WorkoutCard.tsx
index e7639ba..8d9d803 100644
--- a/mobile/src/components/workouts/WorkoutCard.tsx
+++ b/mobile/src/components/workouts/WorkoutCard.tsx
@@ -3,7 +3,7 @@ import { Pressable, View } from 'react-native'
import { router } from 'expo-router'
import { format } from 'date-fns'
import { ChevronRight, Clock, Dumbbell, MoreVertical, TrendingUp } from 'lucide-react-native'
-import { displayVolume, type Workout, workoutDay } from '@lyftr/shared'
+import { displayVolume, type Workout, workoutDay, dayToLocalDate} from '@lyftr/shared'
import { ActionSheet, AppText, Card, ConfirmSheet, IconButton, deleteAction, deleteConfirmProps, editAction } from '../ui'
import { useTheme } from '../../theme/useTheme'
import { client } from '../../lib/lyftr'
@@ -62,7 +62,7 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {
then exercises + volume — three items on one line truncated at 390pt. */}
<View className="flex-row items-center gap-x-2 mt-0.5">
<AppText variant="caption" color="muted" numberOfLines={1}>
- {format(new Date(workoutDay(workout) + 'T12:00:00'), 'MMM d, yyyy')}
+ {format(dayToLocalDate(workoutDay(workout)), 'MMM d, yyyy')}
</AppText>
{durationMin > 0 && (
<>
@@ -121,7 +121,7 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {
<View className="flex-1">
<AppText variant="subheading" numberOfLines={1}>{workout.name}</AppText>
<AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">
- {format(new Date(workoutDay(workout) + 'T12:00:00'), 'MMM d, yyyy')}
+ {format(dayToLocalDate(workoutDay(workout)), 'MMM d, yyyy')}
{durationMin > 0 ? ` · ${durationMin} min` : ''}
{` · ${workout.exercises?.length || 0} exercises`}
</AppText>
diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.ts
index ed64943..fa4490e 100644
--- a/packages/shared/src/client.test.ts
+++ b/packages/shared/src/client.test.ts
@@ -88,3 +88,24 @@ describe('workoutAPI tz_offset_minutes', () => {
expect(calls[0].body.tz_offset_minutes).toBe(0)
})
})
+
+// A workout logged before the offset column existed has no stored offset, so the edit
+// screen names the field with an undefined value. That must reach the server as absent
+// — letting it fall back to the account zone — rather than being stamped with wherever
+// the person editing happens to be standing.
+describe('workoutAPI tz_offset_minutes on legacy rows', () => {
+ it('sends no offset when the caller names the field with no value', async () => {
+ const calls: Array<{ body: any }> = []
+ const client = createClient(memStorage())
+ client.api.defaults.adapter = async (config: any) => {
+ calls.push({ body: JSON.parse(config.data ?? '{}') })
+ return { data: { data: {} }, status: 200, statusText: 'OK', headers: {}, config }
+ }
+ await client.workoutAPI.update(1, {
+ name: 'Legacy row',
+ started_at: '2026-07-01T23:00:00Z',
+ tz_offset_minutes: undefined,
+ })
+ expect('tz_offset_minutes' in calls[0].body).toBe(false)
+ })
+})
diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.ts
index 7b0a087..b92c32a 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -150,15 +150,21 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})
tz_offset_minutes: utcOffsetMinutes(data?.started_at),
}).then(unwrap),
// The offset must describe the instant being sent, so it is stamped only when the
- // caller derived that instant here and now. The mobile edit screen re-picks the date
- // through dayToInstant in this zone and omits the offset, so it gets this device's.
- // A caller that resends the timestamp it loaded passes the stored offset through,
- // because stamping there would move the day on an edit that never touched the date.
+ // caller derived that instant here and now. Keyed on whether the caller mentioned the
+ // field at all, not on its value: the mobile edit screen re-picks the date through
+ // dayToInstant in this zone and omits the offset, so it gets this device's. A caller
+ // that resends the timestamp it loaded names the field and is taken at its word —
+ // including when the value is undefined because the row predates the column. Stamping
+ // there would claim the workout happened where the editing happened; leaving it unset
+ // lets the server fall back to the account zone, which is at least a stored answer
+ // rather than wherever someone opened the form.
update: (id: number, data: any) =>
- api.put<{ data: types.Workout }>(`/workouts/${id}`, {
- ...data,
- tz_offset_minutes: data?.tz_offset_minutes ?? utcOffsetMinutes(data?.started_at),
- }).then(unwrap),
+ api.put<{ data: types.Workout }>(
+ `/workouts/${id}`,
+ 'tz_offset_minutes' in (data ?? {})
+ ? data
+ : { ...data, tz_offset_minutes: utcOffsetMinutes(data?.started_at) },
+ ).then(unwrap),
delete: (id: number) => api.delete(`/workouts/${id}`),
}
diff --git a/packages/shared/src/utils/dateUtils.test.ts b/packages/shared/src/utils/dateUtils.test.ts
index f53a071..c6deb54 100644
--- a/packages/shared/src/utils/dateUtils.test.ts
+++ b/packages/shared/src/utils/dateUtils.test.ts
@@ -1,4 +1,4 @@
-import { todayStr, dayToInstant, instantToDay, entryDay, workoutDay } from './dateUtils'
+import { todayStr, dayToInstant, dayToLocalDate, instantToDay, entryDay, workoutDay } from './dateUtils'
const hours = (from: string, to: string) =>
(new Date(to).getTime() - new Date(from).getTime()) / 3_600_000
@@ -130,3 +130,26 @@ describe('workoutDay — recovered from the recorded offset', () => {
expect(() => workoutDay({ started_at: 'nonsense', tz_offset_minutes: -240 })).not.toThrow()
})
})
+
+describe('dayToLocalDate', () => {
+ it('returns the same calendar day it was given, in local time', () => {
+ const d = dayToLocalDate('2026-07-01')
+ expect(d.getFullYear()).toBe(2026)
+ expect(d.getMonth()).toBe(6)
+ expect(d.getDate()).toBe(1)
+ })
+
+ // The point of the helper. `new Date('2026-07-01T12:00:00')` is parsed as UTC by
+ // pre-iOS 14.5 Safari, which lands on the 2nd anywhere east of UTC+12 — so a stored
+ // day would render as the next day purely because of how it was parsed. Noon leaves
+ // 12 hours of headroom on both sides of the date it names.
+ it('sits at local noon, far from either midnight', () => {
+ expect(dayToLocalDate('2026-07-01').getHours()).toBe(12)
+ })
+
+ it('round-trips through the day formatter', () => {
+ for (const day of ['2026-01-01', '2026-03-08', '2026-11-01', '2026-12-31']) {
+ expect(instantToDay(dayToLocalDate(day).toISOString())).toBe(day)
+ }
+ })
+})
diff --git a/packages/shared/src/utils/dateUtils.ts b/packages/shared/src/utils/dateUtils.ts
index 42f250c..ea3be02 100644
--- a/packages/shared/src/utils/dateUtils.ts
+++ b/packages/shared/src/utils/dateUtils.ts
@@ -73,6 +73,19 @@ export const dayToInstant = (yyyyMmDd: string, previousIso?: string): string =>
).toISOString()
}
+/**
+ * A stored day (YYYY-MM-DD) as a local Date, for formatting it.
+ *
+ * Anchored at local noon so a formatter can never round or shift it across either
+ * midnight, and built from explicit components for the reason dayToInstant spells out
+ * above: `new Date('YYYY-MM-DDTHH:MM:SS')` is parsed as UTC by pre-iOS 14.5 Safari, so
+ * every screen using that string form to render a stored day would show the next day
+ * east of UTC — reintroducing, at display time, the bug this module exists to remove.
+ */
+export const dayToLocalDate = (yyyyMmDd: string): Date => {
+ const [y, m, d] = yyyyMmDd.split('-').map(Number)
+ return new Date(y, (m ?? 1) - 1, d ?? 1, 12, 0, 0, 0)
+}
/**
* The local calendar day `n` days before today.
*
diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx
index 74a2a58..8fd6ebd 100644
--- a/web/src/pages/Dashboard.tsx
+++ b/web/src/pages/Dashboard.tsx
@@ -16,7 +16,7 @@ import { workoutAPI, foodAPI, weightAPI, userAPI, programAPI } from '../services
import { useWorkoutSession } from '../stores/workoutSession'
import { useAuthStore } from '../stores/auth'
import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'
-import { workoutDay, entryDay } from '../utils/dateUtils'
+import { workoutDay, entryDay, dayToLocalDate} from '../utils/dateUtils'
import { useNavigate, Link } from 'react-router-dom'
import * as types from '../types'
import { muscleColor } from '../utils/exerciseUtils'
@@ -205,7 +205,7 @@ export default function Dashboard() {
// Volume chart: slice by selected period, oldest→newest
const chartData = workouts.slice(0, Number(volumePeriod)).reverse().map(w => ({
- date: format(new Date(workoutDay(w) + 'T12:00:00'), 'M/d'),
+ date: format(dayToLocalDate(workoutDay(w)), 'M/d'),
volume: displayVolume(calcVolume(w), settings.weight_unit),
name: w.name,
}))
@@ -272,7 +272,7 @@ export default function Dashboard() {
// Weight sparkline
const sparkData = [...weightLogs].reverse().map(l => ({
- date: format(new Date(entryDay(l) + 'T12:00:00'), 'M/d'),
+ date: format(dayToLocalDate(entryDay(l)), 'M/d'),
weight: displayWeight(l.weight, settings.weight_unit),
}))
@@ -551,7 +551,7 @@ export default function Dashboard() {
<div className="min-w-0">
<p className="text-sm font-semibold text-tx-primary truncate">{lastWorkout.name}</p>
<p className="text-xs text-tx-muted mt-0.5">
- {format(new Date(workoutDay(lastWorkout) + 'T12:00:00'), 'MMM d')}
+ {format(dayToLocalDate(workoutDay(lastWorkout)), 'MMM d')}
{mins > 0 && ` · ${mins} min`}
{totalSets > 0 && ` · ${totalSets} sets`}
{totalVolume > 0 && ` · ${totalVolume.toLocaleString()} ${wUnit}`}
diff --git a/web/src/pages/Food.tsx b/web/src/pages/Food.tsx
index 6ef597d..5db34c4 100644
--- a/web/src/pages/Food.tsx
+++ b/web/src/pages/Food.tsx
@@ -14,7 +14,7 @@ import {
import Loading from '../components/Loading'
import PeriodSelector from '../components/PeriodSelector'
import { foodAPI, userAPI } from '../services/api'
-import { todayStr } from '../utils/dateUtils'
+import { todayStr, dayToLocalDate} from '../utils/dateUtils'
import { MACRO_COLORS } from '../utils/macroColors'
import * as types from '../types'
@@ -155,7 +155,7 @@ export default function Food() {
const calPct = Math.min(100, (totalCals / calTarget) * 100)
const isToday = selectedDate === todayStr()
- const selectedDateObj = new Date(selectedDate + 'T12:00:00')
+ const selectedDateObj = dayToLocalDate(selectedDate)
const prevDate = format(subDays(selectedDateObj, 1), 'yyyy-MM-dd')
const nextDate = format(addDays(selectedDateObj, 1), 'yyyy-MM-dd')
const canGoNext = selectedDate < todayStr()
@@ -423,7 +423,7 @@ export default function Food() {
</defs>
<XAxis
dataKey="date"
- tickFormatter={d => format(new Date(d + 'T12:00:00'), 'M/d')}
+ tickFormatter={d => format(dayToLocalDate(d), 'M/d')}
tick={{ fontSize: 10, fill: 'var(--color-tx-muted)' }}
axisLine={false}
tickLine={false}
@@ -444,7 +444,7 @@ export default function Food() {
fontSize: '12px',
color: 'var(--color-tx-primary)',
}}
- labelFormatter={d => format(new Date(d + 'T12:00:00'), 'MMM d')}
+ labelFormatter={d => format(dayToLocalDate(d), 'MMM d')}
formatter={(val: number, name: string) => [`${Math.round(val)}g`, name]}
cursor={{ stroke: 'rgba(99,102,241,0.15)', strokeWidth: 1 }}
/>
diff --git a/web/src/pages/Weight.tsx b/web/src/pages/Weight.tsx
index 0929016..351677c 100644
--- a/web/src/pages/Weight.tsx
+++ b/web/src/pages/Weight.tsx
@@ -11,7 +11,7 @@ import StepperTile from '../components/ui/StepperTile'
import NumberField from '../components/ui/NumberField'
import { BODYWEIGHT_STEP, clampStep } from '../utils/number'
import { useServerInfiniteList } from '../hooks/useServerInfiniteList'
-import { todayStr, daysAgoStr, dayToInstant, entryDay } from '../utils/dateUtils'
+import { todayStr, daysAgoStr, dayToInstant, entryDay, dayToLocalDate} from '../utils/dateUtils'
import { weightAPI } from '../services/api'
import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs, displayWeight, round1 , weightError, maxWeight } from '../stores/settings'
import * as types from '../types'
@@ -258,7 +258,7 @@ export default function Weight() {
.slice()
.reverse()
.map(l => {
- const d = new Date(entryDay(l) + 'T12:00:00')
+ const d = dayToLocalDate(entryDay(l))
return { ts: d.getTime(), weight: lbsToDisplay(l.weight, settings.weight_unit), date: d }
})
}, [chartLogs, settings.weight_unit])
@@ -424,7 +424,7 @@ export default function Weight() {
<div className="flex items-start gap-3 rounded-xl border border-amber-500/20 bg-amber-500/10 px-4 py-3 text-sm text-amber-400" role="alert">
<AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
<div className="flex-1 min-w-0">
- <p className="font-medium">Already logged on {format(new Date(entryDay(items[0]) + 'T12:00:00'), 'MMM d')} ({displayWeight(items[0].weight, settings.weight_unit)} {wUnit}). Log again anyway?</p>
+ <p className="font-medium">Already logged on {format(dayToLocalDate(entryDay(items[0])), 'MMM d')} ({displayWeight(items[0].weight, settings.weight_unit)} {wUnit}). Log again anyway?</p>
<div className="flex gap-2 mt-2">
<button
type="button"
@@ -555,7 +555,7 @@ export default function Weight() {
{Math.round(displayW)} {wUnit}
</p>
<p className="text-xs text-tx-muted mt-0.5">
- {format(new Date(entryDay(entry) + 'T12:00:00'), 'MMM d, yyyy')}
+ {format(dayToLocalDate(entryDay(entry)), 'MMM d, yyyy')}
</p>
{(deltaLbs !== 0 || entry.notes) && (
<div className="flex items-center gap-x-2 mt-0.5 min-w-0 overflow-hidden">
diff --git a/web/src/pages/WeightDetail.tsx b/web/src/pages/WeightDetail.tsx
index 1dd8f16..e8e0b7d 100644
--- a/web/src/pages/WeightDetail.tsx
+++ b/web/src/pages/WeightDetail.tsx
@@ -7,7 +7,7 @@ import { weightAPI } from '../services/api'
import { useSettingsStore, weightShort, displayWeight, weightError, maxWeight, resolveWeightLbs } from '../stores/settings'
import { useBodyScrollLock } from '../hooks/useBodyScrollLock'
import { useEscapeKey } from '../hooks/useEscapeKey'
-import { todayStr, dayToInstant, entryDay } from '../utils/dateUtils'
+import { todayStr, dayToInstant, entryDay, dayToLocalDate} from '../utils/dateUtils'
import StepperTile from '../components/ui/StepperTile'
import NumberField from '../components/ui/NumberField'
import { BODYWEIGHT_STEP, clampStep } from '../utils/number'
@@ -164,7 +164,7 @@ export default function WeightDetail() {
<span className="text-tx-muted text-lg mb-1">{wUnit}</span>
</div>
<p className="text-sm text-tx-muted mt-1">
- {format(new Date(entryDay(log) + 'T12:00:00'), 'EEEE, MMMM d, yyyy')}
+ {format(dayToLocalDate(entryDay(log)), 'EEEE, MMMM d, yyyy')}
</p>
{log.notes && (
<p className="text-sm text-tx-secondary mt-2 italic">"{log.notes}"</p>
@@ -248,7 +248,7 @@ export default function WeightDetail() {
<div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
<h3 className="font-display font-bold text-lg text-tx-primary mb-1">Delete Entry?</h3>
<p className="text-sm text-tx-muted mb-5">
- {format(new Date(entryDay(log) + 'T12:00:00'), 'MMMM d, yyyy')} · {displayWeight(log.weight, settings.weight_unit)} {wUnit} will be permanently deleted.
+ {format(dayToLocalDate(entryDay(log)), 'MMMM d, yyyy')} · {displayWeight(log.weight, settings.weight_unit)} {wUnit} will be permanently deleted.
</p>
<div className="flex gap-3">
<button
diff --git a/web/src/pages/WorkoutDetail.tsx b/web/src/pages/WorkoutDetail.tsx
index b997d73..cd7e2c3 100644
--- a/web/src/pages/WorkoutDetail.tsx
+++ b/web/src/pages/WorkoutDetail.tsx
@@ -9,7 +9,7 @@ import { workoutAPI } from '../services/api'
import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'
import * as types from '../types'
import { muscleColor } from '../utils/exerciseUtils'
-import { workoutDay } from '../utils/dateUtils'
+import { workoutDay, dayToLocalDate} from '../utils/dateUtils'
function SetChip({ set, isBest, unit }: { set: types.Set; isBest: boolean; unit: string }) {
return (
@@ -154,7 +154,7 @@ export default function WorkoutDetail() {
<div className="min-w-0 flex-1">
<h1 className="font-display font-bold text-xl text-tx-primary leading-tight">{workout.name}</h1>
<p className="text-sm text-tx-muted mt-0.5">
- {format(new Date(workoutDay(workout) + 'T12:00:00'), 'EEEE, MMMM d, yyyy')}
+ {format(dayToLocalDate(workoutDay(workout)), 'EEEE, MMMM d, yyyy')}
</p>
</div>
</div>
diff --git a/web/src/pages/Workouts.tsx b/web/src/pages/Workouts.tsx
index 78dbf65..b12162f 100644
--- a/web/src/pages/Workouts.tsx
+++ b/web/src/pages/Workouts.tsx
@@ -11,7 +11,7 @@ import { useServerInfiniteList } from '../hooks/useServerInfiniteList'
import { workoutAPI } from '../services/api'
import { useSettingsStore, weightShort, displayVolume } from '../stores/settings'
import * as types from '../types'
-import { workoutDay } from '../utils/dateUtils'
+import { workoutDay, dayToLocalDate} from '../utils/dateUtils'
function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; onEdit: (id: number) => void; onDelete: (id: number) => void }) {
const navigate = useNavigate()
@@ -99,7 +99,7 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on
)}
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold text-tx-primary truncate">{workout.name}</p>
- <p className="text-xs text-tx-muted mt-0.5 whitespace-nowrap">{format(new Date(workoutDay(workout) + 'T12:00:00'), 'MMM d, yyyy')}</p>
+ <p className="text-xs text-tx-muted mt-0.5 whitespace-nowrap">{format(dayToLocalDate(workoutDay(workout)), 'MMM d, yyyy')}</p>
<div className="flex items-center gap-x-2 mt-0.5 min-w-0 overflow-hidden">
{durationMin > 0 && (
<span className="flex items-center gap-1 text-xs text-tx-muted whitespace-nowrap">
diff --git a/web/src/services/api.ts b/web/src/services/api.ts
index 61752a1..d7704e1 100644
--- a/web/src/services/api.ts
+++ b/web/src/services/api.ts
@@ -131,15 +131,20 @@ export const workoutAPI = {
tz_offset_minutes: utcOffsetMinutes(data?.started_at),
}).then(res => unwrap(res)),
// The offset must describe the instant being sent, so it is stamped only when the
- // caller derived that instant here and now. A screen that re-picks the date omits it
- // and gets this device's offset; one that resends the timestamp it loaded passes the
- // stored offset through, because stamping there would move the day on an edit that
- // never touched the date.
+ // caller derived that instant here and now. Keyed on whether the caller mentioned the
+ // field at all, not on its value: a screen that re-picks the date omits it and gets
+ // this device's offset, while one that resends the timestamp it loaded names the field
+ // and is taken at its word — including when the value is undefined because the row
+ // predates the column. Stamping there would claim the workout happened where the
+ // editing happened; leaving it unset lets the server fall back to the account zone,
+ // which is at least a stored answer rather than wherever someone opened the form.
update: (id: number, data: any) =>
- api.put<{ data: types.Workout }>(`/workouts/${id}`, {
- ...data,
- tz_offset_minutes: data?.tz_offset_minutes ?? utcOffsetMinutes(data?.started_at),
- }).then(res => unwrap(res)),
+ api.put<{ data: types.Workout }>(
+ `/workouts/${id}`,
+ 'tz_offset_minutes' in (data ?? {})
+ ? data
+ : { ...data, tz_offset_minutes: utcOffsetMinutes(data?.started_at) },
+ ).then(res => unwrap(res)),
delete: (id: number) => api.delete(`/workouts/${id}`),
}
diff --git a/web/src/utils/dateUtils.ts b/web/src/utils/dateUtils.ts
index 42f250c..ea3be02 100644
--- a/web/src/utils/dateUtils.ts
+++ b/web/src/utils/dateUtils.ts
@@ -73,6 +73,19 @@ export const dayToInstant = (yyyyMmDd: string, previousIso?: string): string =>
).toISOString()
}
+/**
+ * A stored day (YYYY-MM-DD) as a local Date, for formatting it.
+ *
+ * Anchored at local noon so a formatter can never round or shift it across either
+ * midnight, and built from explicit components for the reason dayToInstant spells out
+ * above: `new Date('YYYY-MM-DDTHH:MM:SS')` is parsed as UTC by pre-iOS 14.5 Safari, so
+ * every screen using that string form to render a stored day would show the next day
+ * east of UTC — reintroducing, at display time, the bug this module exists to remove.
+ */
+export const dayToLocalDate = (yyyyMmDd: string): Date => {
+ const [y, m, d] = yyyyMmDd.split('-').map(Number)
+ return new Date(y, (m ?? 1) - 1, d ?? 1, 12, 0, 0, 0)
+}
/**
* The local calendar day `n` days before today.
*