From 010c7ddbe09733c27890a759d57c79503d1d2401 Mon Sep 17 00:00:00 2001 From: Bryan Austin Date: Fri, 1 Jun 2018 12:01:34 -0700 Subject: [PATCH] Fix clocks module chronological sorting issue #98 `clock.LocalTime()` sets the location of a `time.Time` object, but doesn't change the point in time. Since `clock.LocalTime()` calls `time.Now()` to create the "local time", what ends up happening is that the first `LocalTime()` is always "before" the second one (because of the order of function calls), leading to unstable sorting. This change does two things to fix chronological sorting. The first is to add a `clock.ToLocal(time.Time)` function that acts like `clock.LocalTime()` for a given time point, so that a single stable time point can be used throughout sorting. The second is to do chronological sorting by comparing the string versions of the local time, which look like (for London vs. SF): 2018-06-01 19:48:26.591550198 +0100 BST vs. 2018-06-01 11:48:26.5915538 -0700 PDT There may be a better way, this feels hacky-ish but works for me on OSX. One remaining downside is that for locations in the same time zone (i.e. Avignon and Barcelona in the default settings), order is determined ~randomly on startup. You could maybe append the location to the string used for comparison to make alphabetical sorting a fallback for equivalent times, but at least they don't jump around anymore. --- clocks/clock.go | 6 +++++- clocks/clock_collection.go | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/clocks/clock.go b/clocks/clock.go index 2ce17e5f..fc4965fc 100644 --- a/clocks/clock.go +++ b/clocks/clock.go @@ -25,7 +25,11 @@ func (clock *Clock) Date() string { } func (clock *Clock) LocalTime() time.Time { - return time.Now().In(clock.Location) + return clock.ToLocal(time.Now()) +} + +func (clock *Clock) ToLocal(t time.Time) time.Time { + return t.In(clock.Location) } func (clock *Clock) Time() string { diff --git a/clocks/clock_collection.go b/clocks/clock_collection.go index d81b18ff..a1c226ea 100644 --- a/clocks/clock_collection.go +++ b/clocks/clock_collection.go @@ -2,6 +2,7 @@ package clocks import ( "sort" + "time" ) type ClockCollection struct { @@ -28,10 +29,11 @@ func (clocks *ClockCollection) SortedAlphabetically() { } func (clocks *ClockCollection) SortedChronologically() { + now := time.Now() sort.Slice(clocks.Clocks, func(i, j int) bool { clock := clocks.Clocks[i] other := clocks.Clocks[j] - return clock.LocalTime().Before(other.LocalTime()) + return clock.ToLocal(now).String() < other.ToLocal(now).String() }) }