Date and Time

1 Reading Date and Time

This is how elisp stores a time:

(current-time) => (21209 38073 267139)

The first two numbers are the high and low bits of an integer number giving seconds since the epoch (0:00 January 1, 1970 UTC). The last number is microseconds and may be ommitted. There may be a fourth number representing picoseconds.
decode-time puts this into a more user friendly format:

(decode-time (current-time)) => (30 38 20 17 1 2014 5 nil 0)

The individual values are (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE) DOW is DOW of week DST is t if Daylight saving time is in effect ZONE is an integer indicating the number of seconds east of Greenwich.
format-time-string gives a more everyday format:

(format-time-string "%d/%m/%Y %H:%M:%S" (current-time)) => "17/01/2014 20:38:43"

Or, if you’re really in a hurry:

(current-time-string) => "Fri Jan 17 20:38:54 2014"

2 Setting a Date or Time

Set a time using date-to-time

(date-to-time "May 20 2011 19:30:00") => (19926 45864)

Note that the date strings format is dependent on your machine’s locale settings. For example, the following may be necessary. For more about locales, read this post.

(date-to-time "20 May 2011 19:30:00")

Enter a date using parse-time-string

(setq concert (parse-time-string "May 20 2011 19:30:00")) => (0 30 19 20 5 2011 nil nil nil)

Unlike date-to-time, parse-time-string allows you to omit the time value :

(setq birthday (parse-time-string "July 29 1953")) => (nil nil nil 29 7 1953 nil nil nil)

Here are some times:

(setq five-seconds (seconds-to-time 5))
(setq ninety-minutes (seconds-to-time (* 60 90)))
(setq one-day (seconds-to-time (* 60 60 24)))

The last can be more easily entered as:

(setq one-day (days-to-time 1))

Which leads to

(setq one-week (days-to-time 7))

and so on…

3 Converting Time Values

Use encode-time and decode-time to switch between formats

(encode-time 0 30 19 20 5 2011) => (19926 45864)
(decode-time '(19926  45864)) => (0 30 19 20 5 2011 5 t 3600)

4 Calculations on Dates and Times

Use time-add to add two times together.
Here’s the time a concert starts

(setq concert (date-to-time "May 20 2011 19:30:00"))

Suppose the concert lasts two hours (or 2 x 60 x 60 seconds). You can work out the time the concert ends as follows

(time-add concert (seconds-to-time (* 2 60 60)))

Let’s just check that worked

(format-time-string "%d/%m/%Y %H:%M:%S" (time-add concert (seconds-to-time (* 2 60 60)))) => "20/05/2011 21:30:00"

Suppose you know the start and end times of the concert. Use time-subtract to work out the duration:

(setq concert-start (date-to-time "May 20 2011 19:30:00"))
(setq concert-end (date-to-time "May 20 2011 22:25:00"))
(format-time-string "%H:%M:%S"(time-subtract concert-end concert-start)) => "02:55:00"

See Also

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.