From 05b417acfa10a970a442b264aa4e9037cb26721b Mon Sep 17 00:00:00 2001 From: Michael Mayer Date: Tue, 26 Jan 2021 13:00:54 +0100 Subject: [PATCH] Metadata: Apply existing time zone when changing TakenAt --- internal/entity/photo.go | 29 ++++++++++++++++------------- internal/entity/photo_test.go | 16 ++++++++++++---- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/internal/entity/photo.go b/internal/entity/photo.go index 129e9a1c9..196b33292 100644 --- a/internal/entity/photo.go +++ b/internal/entity/photo.go @@ -857,6 +857,11 @@ func (m *Photo) SetTakenAt(taken, local time.Time, zone, source string) { return } + // Default local time to taken if zero or invalid. + if local.IsZero() || local.Year() < 1000 { + local = taken + } + // Round times to avoid jitter. taken = taken.Round(time.Second).UTC() local = local.Round(time.Second) @@ -866,23 +871,21 @@ func (m *Photo) SetTakenAt(taken, local time.Time, zone, source string) { return } + // Set UTC time and date source. m.TakenAt = taken m.TakenSrc = source - if local.IsZero() || local.Year() < 1000 { - m.TakenAtLocal = m.TakenAt - } else { - m.TakenAtLocal = local - } - - // Set time zone. - if zone != "" { + // Convert time and set zone as needed. + if loc, err := time.LoadLocation(zone); err == nil && zone != "" { + // Apply new time zone. m.TimeZone = zone - } - - // Apply time zone. - if m.TimeZone != "" { - m.TakenAt = m.GetTakenAt() + m.TakenAtLocal = m.TakenAt.In(loc) + } else if m.TimeZone == "" { + // Ignore time zone. + m.TakenAtLocal = local + } else if loc, err := time.LoadLocation(m.TimeZone); err == nil { + // Apply existing time zone. + m.TakenAtLocal = m.TakenAt.In(loc) } m.UpdateDateFields() diff --git a/internal/entity/photo_test.go b/internal/entity/photo_test.go index 222822732..e4becfee0 100644 --- a/internal/entity/photo_test.go +++ b/internal/entity/photo_test.go @@ -575,11 +575,19 @@ func TestPhoto_SetTakenAt(t *testing.T) { assert.Equal(t, time.Date(2013, 11, 11, 9, 7, 18, 0, time.UTC), m.TakenAt) assert.Equal(t, time.Date(2013, 11, 11, 9, 7, 18, 0, time.UTC), m.TakenAtLocal) - m.SetTakenAt(time.Date(2013, 11, 11, 9, 7, 18, 0, time.UTC), - time.Date(2013, 11, 11, 9, 7, 18, 0, time.UTC), "Europe/Berlin", SrcName) + newTime := time.Date(2013, 11, 11, 9, 7, 18, 0, time.UTC) + newLoc, _ := time.LoadLocation("Europe/Berlin") - assert.Equal(t, time.Date(2013, 11, 11, 8, 7, 18, 0, time.UTC), m.TakenAt) - assert.Equal(t, time.Date(2013, 11, 11, 9, 7, 18, 0, time.UTC), m.TakenAtLocal) + m.SetTakenAt(newTime, newTime, "Europe/Berlin", SrcName) + + /* + t.Logf("TakenAt: %s\n", m.TakenAt) + t.Logf("TakenAtLocal: %s\n", m.TakenAtLocal) + t.Logf("Expected: %s\n", newTime.In(newLoc)) + */ + + assert.Equal(t, newTime, m.TakenAt) + assert.Equal(t, newTime.In(newLoc), m.TakenAtLocal) }) t.Run("time > max year", func(t *testing.T) { m := PhotoFixtures.Get("Photo15")