spencermountain / spacetime

A lightweight javascript timezone library
http://spacetime.how/
Other
3.97k stars 184 forks source link

s.diff(d, 'days') is off by one #371

Closed joepavitt closed 1 year ago

joepavitt commented 1 year ago

We are using spacetime on our website, and have a piece of text counting the number of days until our next webinar/event.

I've added logging to sanity check this, and diff() is consistently out by one day.

const postDate = spacetime(date)
console.log(date)
const now = spacetime.now()
console.log(now)

console.log(now.dayName())
console.log(postDate.dayName())

const days = now.diff(postDate, 'day')

console.log(days)

Logs:

SpaceTime {
  epoch: 1675900800000,
  tz: 'europe/london',
  silent: true,
  british: undefined,
  _weekStart: 1,
  _today: {}
}

SpaceTime {
  epoch: 1675791134992,
  tz: 'europe/london',
  silent: true,
  british: undefined,
  _weekStart: 1,
  _today: {}
}

tuesday
thursday
1
spencermountain commented 1 year ago

hey Joe - thanks for the issue. I've heard a lot of neat things about node-red.

Think this is a preferred response, but plz correct me if you feel otherwise:

const now = spacetime('2023-02-07T18:00:00', 'europe/london')
const event = spacetime('2023-02-09', 'europe/london')
console.log(now.format('now: {day-nice} {time}'))
console.log(event.format('event: {day-nice} {time}'))

const days = now.diff(event, 'days')
const hours = now.diff(event, 'hours')
console.log(`${days} days, or ${hours} hours`)

// now: Tue Feb 7th 6:00pm
// event: Thu Feb 9th 12:00am
// 1 days, or 30 hours

30 hours is 1 day.

I think the call you'd prefer is .since()

event.since(now).diff
// { years: 0, months: 0, days: 1, hours: 6, minutes: 0, seconds: 0 },

cheers

joepavitt commented 1 year ago

Thanks Spencer, interesting perspective.

As its Tuesday today, if someone asked me, "how many days until Thursday?", I would, personally, say 2, independent of the time of day.

We've fixed it for now by just adding 1 to the result, as I'm assuming you're just always discarding the remaining hours, so that would do the trick?

spencermountain commented 1 year ago

hey - if the time of day doesn't matter, i would do now.startOf('day') before the calculation that way the comparison will be like-to-like cheers

joepavitt commented 1 year ago

That'll do it - thanks!