[quiz] [QUIZ 5b & 5e] Date differences, and betting

Carl c.groner at gmail.com
Tue Jul 24 02:08:33 UTC 2007


Wow, no takers, huh.
With all the talk that has been going around about lisp lately, this
list is surprisingly quiet.

I suppose I might as well post my attempt. Keep in mind, i'm new to
lisp so it may not be very "lispy". I'm sure someone will shortly make
me feel dumb by posting a two liner with better error handling  < | :)

---- start ----
(defun date-to-time (date &key (tz nil))
"Convert date to timestamp. Date expected to be formatted as: Sat Jul 20 2007 ,
using 3 letter abbreviations for day of week and month"
  (let* ((date-list (read-from-string (concatenate 'string "(" date ")")))
	 (utime (encode-universal-time 0 0 0 (caddr date-list)
				       (+ (position (cadr date-list)
			 '(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)) 1)
				       (cadddr date-list) tz)))
    (if (equal (seventh (multiple-value-list (decode-universal-time utime)))
	       (position (car date-list) '(Mon Tue Wed Thu Fri Sat Sun)))
	utime
	(error "Supplied day (~S) does not match calculated day of week for ~S)"
	       (first date-list) (rest date-list) ))))


(defun days-diff (start end)
"Calculate difference in days between the two provided dates. Dates
must be in the form accepted by date-to-time"
    (/ (- (date-to-time end) (date-to-time start)) 60 60 24))

---- end ---

CL-USER> (days-diff "Wed Oct 16 2002" "Wed Oct 23 2002")
7
CL-USER> (days-diff "Wed Oct 16 2002" "Tue Oct 16 2001")
-365
CL-USER> (days-diff "Thu Jul 19 2007" "Mon Jul 23 2007")
4

Comments or suggestions welcome.

Cheers,
Carl.

On 7/19/07, Larry Clapp <larry at theclapp.org> wrote:
> Beginner:
>
> Adapted from Perl Quiz #2:
> [ http://perl.plover.com/~alias/list.cgi?mss:11:200210:ccbcblpijjjcnhnkabep ]
>
> Write a function, days-diff, to compute the time difference, in days,
> between two dates.  The dates will be strings in the format
>
>         Wed Oct 16 2002
>
> For example:
>
>         (days-diff "Wed Oct 16 2002" "Wed Oct 23 2002")
>         => 7
>
>         (days-diff "Wed Oct 16 2002" "Tue Oct 16 2001")
>         => -365
>
> Error checking: at minimum, signal an error if either value is
> unparsable or internally inconsistent (e.g. if 10/16/2002 is not, in
> fact, a Wednesday).  More advanced users can establish useful
> restarts.
>
> Dependencies on your Lisp's time functions are okay.
>
--8<-- message cut -->8--



More information about the Quiz mailing list