The Common Lisp and Unix epochs

The Common Lisp epoch begins at 00:00 on January 1, 1900, GMT. get-universal-time returns a universal time, defined as the number of seconds elapsed since then.

The Unix epoch begins at 00:00 on January 1, 1970, GMT. time() returns the number of seconds elapsed since then.

It’s easy to get the difference between a Common Lisp universal time and a Unix epoch timestamp:

* (encode-universal-time 0 0 0 1 1 1970 0)
2208988800

When working with Unix epoch timestamp data, it’s easy to write conversion functions:

(defvar *unix-epoch-difference*
  (encode-universal-time 0 0 0 1 1 1970 0))

(defun universal-to-unix-time (universal-time)
  (- universal-time *unix-epoch-difference*))

(defun unix-to-universal-time (unix-time)
  (+ unix-time *unix-epoch-difference*))

(defun get-unix-time ()
  (universal-to-unix-time (get-universal-time)))

Comparing CL output to the shell:

* (get-unix-time)
1318685294
$ date +%s
1318685294

(My CL implementation doesn’t constant-fold the call to encode-universal-time. Bummer.)