Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ parameter and result types, not just their source-level shape. Use

## Standard library additions and changes

- `std/times` adds `anchoredBetween`, which returns an `AnchoredInterval`:
the difference between two `DateTime` values counted from the first one,
so that `a + anchoredBetween(a, b) == b` holds in both directions.
`between` keeps `between(a, b) == -between(b, a)` and guarantees the round
trip only for `a <= b`.

[//]: # "Additions:"

- On Windows, `osproc.startProcess` now raises `OSError` when `command` is a
Expand Down
85 changes: 83 additions & 2 deletions lib/pure/times.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2456,8 +2456,13 @@ proc between*(startDt, endDt: DateTime): TimeInterval =
## `TimeInterval`. The following guarantees about the result is given:
##
## - All fields will have the same sign.
## - If `startDt.timezone == endDt.timezone`, it is guaranteed that
## `startDt + between(startDt, endDt) == endDt`.
## - If `startDt.timezone == endDt.timezone` and `startDt <= endDt`, it is
## guaranteed that `startDt + between(startDt, endDt) == endDt`.
## - `between(startDt, endDt) == -between(endDt, startDt)`. When
## `startDt > endDt`, the difference is counted from the earlier `endDt`,
## so `startDt + between(startDt, endDt)` can differ from `endDt`
## (for example `between(2016-03-01, 2015-03-25)` is
## `-11 months and -5 days`, and 2016-03-01 plus that is 2015-03-27).
## - If `startDt.timezone != endDt.timezone`, then the result will be
## equivalent to `between(startDt.utc, endDt.utc)`.
runnableExamples:
Expand All @@ -2466,6 +2471,10 @@ proc between*(startDt, endDt: DateTime): TimeInterval =
var ti = initTimeInterval(years = 2, weeks = 1, hours = 3, seconds = 15)
doAssert between(a, b) == ti
doAssert between(a, b) == -between(b, a)
##
## See also:
## * `anchoredBetween proc <#anchoredBetween,DateTime,DateTime>`_ for a
## difference that leads from `startDt` to `endDt` in both directions

result = default(TimeInterval)
if startDt.timezone != endDt.timezone:
Expand Down Expand Up @@ -2761,6 +2770,78 @@ proc `+=`*(t: var Time, b: TimeInterval) =
proc `-=`*(t: var Time, b: TimeInterval) =
t = t - b

type
AnchoredInterval* = distinct TimeInterval
## The difference between two `DateTime` values counted from the first
## one (the anchor), as returned by `anchoredBetween`. Adding it to the
## anchor gives the second value, in either direction. Unlike
## `TimeInterval`, it has no unary `-`: the calendar difference counted
## back from the second value is in general not the negation. Use
## `TimeInterval(i)` to read its fields.

proc `==`*(a, b: AnchoredInterval): bool {.borrow.}
proc `$`*(i: AnchoredInterval): string {.borrow.}

proc `+`*(dt: DateTime, i: AnchoredInterval): DateTime =
## Adds `i` to `dt`, like `dt + TimeInterval(i)`. If `dt` is the
## anchor of `i`, the result is the second argument of the
## `anchoredBetween` call that created `i`.
dt + TimeInterval(i)

proc anchoredBetween*(startDt, endDt: DateTime): AnchoredInterval =
## Gives the difference between `startDt` and `endDt` counted from
## `startDt`, in either direction. The following guarantees are given:
##
## - `startDt + anchoredBetween(startDt, endDt) == endDt`, also when
## `startDt > endDt` and when the timezones differ (the calendar fields
## are counted in `startDt.timezone`).
## - All fields have the same sign.
##
## Whole months are counted first, then whole days, and the rest is given
## in hours and smaller units; `weeks` is always 0.
##
## `between` can split the same difference into other fields: it counts a
## negative difference from the earlier date, and it does not let the
## monthday overflow of `+` take part. `anchoredBetween(a, b)` is in
## general not `-anchoredBetween(b, a)`.
##
## See also:
## * `between proc <#between,DateTime,DateTime>`_
runnableExamples:
let a = dateTime(2016, mMar, 1, zone = utc())
let b = dateTime(2015, mMar, 25, zone = utc())
doAssert a + anchoredBetween(a, b) == b
doAssert $anchoredBetween(a, b) == "-11 months and -7 days"
doAssert $anchoredBetween(b, a) == "11 months and 5 days"
doAssert $between(a, b) == "-11 months and -5 days"

let forward = startDt <= endDt
let step = if forward: 1 else: -1
template notPast(dt: DateTime): bool =
if forward: dt <= endDt else: dt >= endDt
let target = endDt.inZone(startDt.timezone)
var months = (target.year - startDt.year) * 12 +
(target.month.ord - startDt.month.ord)
template atMonths(m: int): DateTime =
startDt + initTimeInterval(months = m)
while not notPast(atMonths(months)): months -= step
while notPast(atMonths(months + step)): months += step
var days = int((endDt - atMonths(months)).inDays)
template atDays(d: int): DateTime =
startDt + initTimeInterval(months = months, days = d)
while not notPast(atDays(days)): days -= step
while notPast(atDays(days + step)): days += step
# What is left is shorter than one calendar day of `startDt.timezone`
# (at most 25 hours); it is added as an exact duration.
let rest = (endDt - atDays(days)).toParts
result = AnchoredInterval(initTimeInterval(
years = months div 12, months = months mod 12, days = days,
hours = int(rest[Weeks] * 7 * 24 + rest[Days] * 24 + rest[Hours]),
minutes = int(rest[Minutes]), seconds = int(rest[Seconds]),
milliseconds = int(rest[Milliseconds]),
microseconds = int(rest[Microseconds]),
nanoseconds = int(rest[Nanoseconds])))

#
# Iso week
#
Expand Down
35 changes: 35 additions & 0 deletions tests/stdlib/ttimes.nim
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,41 @@ block: # ttimes
check getDayOfWeek(01, mJan, 2000) == dSat
check getDayOfWeek(01, mJan, 2021) == dFri

block: # anchoredBetween - month ends and leap days, both directions
var starts, ends: seq[DateTime]
let d0 = dateTime(2016, mJan, 1, zone = utc())
for i in countup(0, 365, 5): starts.add d0 + i.days
for y in 2015 .. 2017:
for m in Month:
ends.add dateTime(y, m, 1, zone = utc())
ends.add dateTime(y, m, getDaysInMonth(m, y), zone = utc())
for a in starts:
for b in ends:
let i = anchoredBetween(a, b)
doAssert a + i == b, $(a, b, i)
let t = TimeInterval(i)
doAssert (t.years >= 0 and t.months >= 0 and t.days >= 0) or
(t.years <= 0 and t.months <= 0 and t.days <= 0), $(a, b, i)

block: # anchoredBetween - #26825
let a = dateTime(2016, mMar, 1, zone = utc())
let b = dateTime(2015, mMar, 25, zone = utc())
doAssert a + between(a, b) != b
doAssert a + anchoredBetween(a, b) == b
doAssert TimeInterval(anchoredBetween(a, b)) == -11.months - 7.days

block: # anchoredBetween - dst and times of day
for zone in ["Europe/Stockholm", "America/Belem"]:
usingTimezone(zone):
var ds: seq[DateTime]
for d in [dateTime(2018, mMar, 24), dateTime(2018, mOct, 27),
dateTime(1987, mOct, 24)]:
for m in countup(0, 48 * 60, 330): ds.add d + m.minutes
for a in ds:
for b in ds:
doAssert a + anchoredBetween(a, b) == b, $(a, b)
doAssert a + anchoredBetween(a, b.utc) == b, $(a, b)

block: # between - simple
let x = initDateTime(10, mJan, 2018, 13, 00, 00)
let y = initDateTime(11, mJan, 2018, 12, 00, 00)
Expand Down
Loading