about summary refs log tree commit diff
path: root/users/sterni/blërg/datetime.bqn
blob: 76774a771a8df10842232d9b0544b3e970058b71 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# SPDX-FileCopyrightText: Copyright © 2024-2025 sterni
# SPDX-License-Identifier: GPL-3.0-only
#
# Unnamed Date & Time Library
#
# Proleptic Gregorian Calendar and Astronomical Year Numbering

⟨_join⟩ ⇐ •Import "string.bqn"
⟨Rem,QuotRem,Tr,ToMixedRadix⟩ ⇐ •Import "integer.bqn"

YearDays ← {((0⊸<+×⟜365)𝕩)+´Tr 4‿(-100)‿400÷˜𝕩-𝕩>0}
daySecs ← 60×60×24
epochDelta ← daySecs×YearDays 1970

IsDiv ← 0⊸=∘|
IsLeap ← 4⊸IsDiv ∧ (400⊸IsDiv ∨ (¬ 100⊸IsDiv))
MonthLengths ← {31‿(28+IsLeap 𝕩)‿31‿30‿31‿30‿31‿31‿30‿31‿30‿31}

# TODO(sterni): can this idea be implemented in a nicer way?
DaysAndTime ← {r|⌾(1⊸↓) (⊢ - (« (∨`0⊸>)⌾⌽)) (r←∞‿24‿60‿60) ToMixedRadix epochDelta+𝕩}

FromUnix ⇐ {
  days‿hour‿minute‿second ← DaysAndTime 𝕩

  repeating ← (⊢ ⋈ (YearDays⟜(2⊸×) - YearDays))¨ 4‿100‿400
  # TODO(sterni): figure out why days-1 if >0
  # fold gives us years to current year from 0, so trunc to -∞ for start of year
  year ← +´⌊365‿1÷˜(days-days>0)‿0 {r‿s 𝕊 yy‿yd:(yd Rem r)∾s+yy×Tr r÷yd}˜´ repeating
  daysInYear ← days-YearDays year

  ml ← MonthLengths year
  month ← 1+daysInYear  ⊑∘/∘< +`ml
  day ← 1+daysInYear-+´(month-1)↑ml

  year‿month‿day‿hour‿minute‿second ⇐
}

ToUnix ⇐ {
  days ← (YearDays 𝕩.year)+(+´(𝕩.month-1)↑MonthLengths 𝕩.year)+𝕩.day-1
  epochDelta-˜+´daySecs‿3600‿60‿1×days‿𝕩.hour‿𝕩.minute‿𝕩.second
}

# Format (10⋆𝕨)|𝕩 with leading 0 so the result always has 𝕨 digits
FmtDigits ← {'0'+⌽⌊10|𝕩÷10⋆↕𝕨}


ToIso8601Date ← {
  "year does not fit in YYYY format"!(9999⊸≥ ∧ 0⊸≤) 𝕩.year
  "-" _join 4‿2‿2 FmtDigits¨ 𝕩.year‿𝕩.month‿𝕩.day
}
ToIso8601Time ← {":" _join 2⊸FmtDigits¨ 𝕩.hour‿𝕩.minute‿𝕩.second}
ToRfc3339 ⇐ {"Z"∾˜ "T" _join (ToIso8601Date ⋈ ToIso8601Time) 𝕩}

# exposed for test suite
⟨YearDays,epochDelta,IsLeap⟩ ⇐