summaryrefslogtreecommitdiff
path: root/src/dates.scm
blob: a70aa011f810926ada5c239e544a0cc5f6bf3982 (plain)
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
(define-module (src dates)
  #:use-module (ice-9 format)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-19)
  #:export (string/ISO->date
            date->string/RFC3339
            unix-date
            newest
            find-newest
            date>?))

(define (string/ISO->date string)
  (string->date string "~Y-~m-~d"))

(define (date->string/RFC3339 date)
  (call-with-output-string
    (lambda (p)
      (let* ((offset           (abs (date-zone-offset date)))
             (rem-h-seconds    (modulo offset (* 60 60)))
             (offset-hours     (floor (/ (- offset rem-h-seconds) 60 60)))
             (rem-m-seconds    (modulo rem-h-seconds 60))
             (offset-minutes   (floor (/ (- rem-h-seconds rem-m-seconds) 60))))
       (format
         p
         "~4,'0d-~2,'0d-~2,'0dT~2,'0d:~2,'0d:~2,'0d~:[Z~;~c~2,'0d:~2,'0d~]"
         (date-year date)
         (date-month date)
         (date-day date)
         (date-hour date)
         (date-minute date)
         (date-second date)
         (not (= 0 (date-zone-offset date)))
         (if (< 0 (date-zone-offset date)) #\+ #\-)
         offset-hours
         offset-minutes)))))

(define unix-date (string/ISO->date "1970-01-01"))

(define (newest a b) (if (time>? (date->time-utc a) (date->time-utc b)) a b))

(define (date>? a b)
  (time>? (date->time-utc a) (date->time-utc b)))

(define (find-newest dates) (reduce newest unix-date dates))