Comparing dates in a racket

Are there any built-in functions in racket to compare two dates?

If not, can anyone tell me how to write a function to compare two dates in a racket. I am very new to functional programming languages, please help.

+3


source to share


3 answers


To check if two objects are the same and look the same, use equal?

. Scheme and Racket (language) does time in different ways. Scheme has SRFI-19 , while Racket has a date object

Scheme

#!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

#!racket/base

(equal? (seconds->date 123) 
        (seconds->date 123)) 
; ==> #t

      

+3


source


Built for Racket

Racket has a built-in structure date

:

(struct date (  second
                minute
                hour
                day
                month
                year
                week-day
                year-day
                dst?
                time-zone-offset)

      

but not particularly good functions for working with dates programmatically, that is, if you want to know the date in five minutes, you have to do whatever it takes to wrap minutes, hours, days, weeks, years and daylight saving time.

Comparison with course grade

The comparison can be dated with eq?

or equal?

or the eqv?

same as with any other type struct

.

#lang racket

require racket/date)

(define then (current-date))

(define now (current-date))

      

and is used:

> (eq? then now)
#f
> (eq? then then)
#t

      



This is great if you care about nanosecond granularity, not what you need more than if there were two dates on the same day.

Comparison with fine grain

To compare dates on a day-to-day basis, you need 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))))

      

This can be used in:

"scratch.rkt"> (same-day? then now)
#t

      

In all seriousness

Working with dates is really hard if you are doing work that really matters. Libraries like Joda Time exist in languages ​​like Java when the questions are correct. Don't launch rockets based on your home library.

+3


source


+2


source







All Articles