(module timestamp mzscheme (provide (all-defined)) (require (only (lib "13.ss" "srfi") string-filter)) (require (file "util.ss")) (define get-timestamp (lambda () (let* ([date (seconds->date (current-seconds))] [year (date-year date)] [month (date-month date)] [day (date-day date)] [hour (date-hour date)] [minutes (date-minute date)] [seconds (date-second date)] [fmt-2 "~a"] [fmt-1 "0~a"] [choose-fmt (lambda (n) (if (< n 10) fmt-1 fmt-2))] [month-fmt (choose-fmt month)] [day-fmt (choose-fmt day)] [hour-fmt (choose-fmt hour)] [minutes-fmt (choose-fmt minutes)] [seconds-fmt (choose-fmt seconds)]) (format (sa "~a-" month-fmt "-" day-fmt " " hour-fmt ":" minutes-fmt ":" seconds-fmt) year month day hour minutes seconds)))) (define timestamp->string (lambda (s) (string-filter char-numeric? s))) (define add-number-strings (lambda (s1 s2) (let ([n1 (string->number s1)] [n2 (string->number s2)]) (number->string (+ n1 n2))))) (define leap-year? (lambda (year) (let ([n (string->number year)]) (and (zero? (modulo n 4)) (or (not (zero? (modulo n 100))) (zero? (modulo n 400))))))) (define inc-month (lambda (month) (let* ([n (number->string month)] [inc-n (if (eqv? n 12) 1 (add1 n))]) (number->string inc-n)))) (define maybe-inc-month (lambda (month day days mo-days) (let ([new-days (add-number-strings day (number->string days))]) (if (> (string->number new-days) mo-days) (values (inc-month month) (- new-days mo-days)) (values month new-days))))) (define add-days-to-month-and-day ; assumes we span two months at most (lambda (year month day days) (case month [("1" "3" "5" "7" "8" "10" "12") (maybe-inc-month month day days 31)] [("4" "6" "9" "11") (maybe-inc-month month day days 30)] [else ; February (if (leap-year? year) (maybe-inc-month month day days 29) (maybe-inc-month month day days 28))]))) (define inc-year-string (lambda (year) (let ([n (string->number year)]) (number->string (add1 n))))) (define add-days-to-timestamp ; TODO -validate input (lambda (ts days) (let* ([date (substring ts 0 10)] [time (substring ts 11 19)] [year (substring date 0 4)] [month (substring date 5 7)] [day (substring date 8 10)]) (let*-values ([(new-month new-day) (add-days-to-month-and-day year month day days)] [(_) (printf "~a ~a~n" new-month new-day)] [(new-year) (if (and (string=? month "12") (string=? new-month "1")) (inc-year-string year) year)]) (sa new-year "-" new-month "-" new-day " " time))))) (define date->string (let ([number->string2 (lambda (n) (let ([s (number->string n)]) (if (< n 10) (sa "0" s) s)))]) (lambda (d) (apply string-append (map number->string2 (list (date-year d) (date-month d) (date-day d) (date-hour d) (date-minute d) (date-second d))))))) ; define once at load time (define curr-date-string (date->string (seconds->date (current-seconds)))) )