Elisp: Format Date Time

By Xah Lee. Date: . Last updated: .

This page shows you how to print current date time in various formats.

If you want to parse date/time, see: Elisp: Parsing Date Time.

Format yyyy-mm-dd

If you want the format to be yyyy-mm-dd, use (format-time-string "%Y-%m-%d"). Example:

(defun insert-date ()
  "Insert current date yyyy-mm-dd."
  (interactive)
  (insert (format-time-string "%Y-%m-%d")))

Full ISO 8601 Format

In many web tech spec (For example, Atom Webfeed Format), a full ISO 8601 format is required, like this: 2010-11-28T13:55Z. You can code it like this:

(defun insert-date-time ()
  "Insert current date-time string in full ISO 8601 format.
Example: 2010-11-29T23:23:35-08:00"
  (interactive)
  (insert
   (concat
    (format-time-string "%Y-%m-%dT%T")
    ((lambda (x) (concat (substring x 0 3) ":" (substring x 3 5)))
     (format-time-string "%z")))))

Unix Time Format

To print Unix time format (i.e. number of seconds since .), use %s. Like this:

;; unix time
(format-time-string "%s") ; "1291104066"

Names for Month and Week

You can also print names for month and week, both full name or abbreviation.

;; full month name
(format-time-string "%B") ; "November"

;; abbreviated month name
(format-time-string "%b") ; "Nov"
;; full week name
(format-time-string "%A") ; "Tuesday"

;; abbreviated week name
(format-time-string "%a") ; "Tue"

Ordinal Date Format

format-time-string also supports ordinal date format. For example:

(format-time-string "%Y-%j") ; "2010-334" for 2010-11-30

(info "(elisp) Time Parsing")

(info "(elisp) Time of Day")

Liket it? Put $5 at patreon. Or Buy Xah Emacs Tutorial. Thanks.