Emacs Lisp: 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: Emacs Lisp: 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."
  (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"
    (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")

Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs