Are there any built in functions in racket to compare 2 dates?
If not can anyone tell me how to write a function to compare 2 dates in racket. I am very new to functional programming languages please help.
Are there any built in functions in racket to compare 2 dates?
If not can anyone tell me how to write a function to compare 2 dates in racket. I am very new to functional programming languages please help.
Racket has a built-in date
structure:
(struct date ( second
minute
hour
day
month
year
week-day
year-day
dst?
time-zone-offset)
but not particularly good functions for dealing with dates programmaticly, that is if you want to know the date in five minutes, you have to do all the wrapping of minutes, hours, days, weeks, years, and daylight savings time yourself.
Comparison can be on dates can be done with eq?
or equal?
or eqv?
just as with any other struct
type.
#lang racket
require racket/date)
(define then (current-date))
(define now (current-date))
and used:
> (eq? then now)
#f
> (eq? then then)
#t
This is great if you care about nano-second granularity, not if you care about anything bigger like seeing if two dates are the same day.
To compare dates at the level of days you have to write something like:
(define (same-day? date1 date2)
(and (= (date-day date1)
(date-day date2))
(= (date-month date1)
(date-month date2))
(= (date-year date1)
(date-year date2))))
That can be used in:
"scratch.rkt"> (same-day? then now)
#t
Working with dates is really hard if it you're doing work that really matters. Libraries like Joda Time exist in languages like Java when getting dates right matters. Don't launch missiles based on your home grown date library.
To check if two objects are the same type and happen to look the same you use equal?
. Scheme and Racket (the language) does time differently. Scheme has SRFI-19 while Racket has a date object
#!r6rs
(import (rnrs base)
(srfi :19))
(equal? (make-time time-utc 0 123)
(make-time time-utc 0 123))
; ==> #t
// perhaps faster equality test (not guaranteed to be faster)
(time=? (make-time time-utc 0 123)
(make-time time-utc 0 123))
; ==> #t
#!racket/base
(equal? (seconds->date 123)
(seconds->date 123))
; ==> #t
If you already have absolute seconds, you can simply compare with the usual integer functions like =
, <=
, and so on.
If you have date parts like month, day, year, then convert that to seconds so you can do the simple thing above. To do so:
date
struct.date->seconds
.Or more simply, use find-seconds
, which is (roughly) the composition of these.
© 2022 - 2024 — McMap. All rights reserved.
racket/date
andsrfi/19
. If those are insufficient for your needs, take a look at thegregor
package. – Surcingle