ErgoEmacsEmacsLispBlogEmacsLispBuy Tutorial

Emacs Lisp: Date/Time String

, , …,

This page shows you how to print current date time in various formats. If you want to parse date/time stamp, see: Emacs Lisp: Writing a Date Time String Parsing Function.

Use format-time-string to print date time.

ISO 8601 Format yyyy-mm-dd

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

(defun insert-date ()
  "Insert current date yyyy-mm-dd."
  (interactive)
  (when (region-active-p)
    (delete-region (region-beginning) (region-end) )
    )
  (insert (format-time-string "%Y-%m-%d"))
  )

Full ISO 8601 Format

In many web tech spec (⁖ 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
See: URL `http://en.wikipedia.org/wiki/ISO_8601'
"
  (interactive)
  (when (region-active-p)
    (delete-region (region-beginning) (region-end) )
    )
  (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 1970-01-01.), use %s. Like this:

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

Names for Month & Week

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

(format-time-string "%B %b") ; "November Nov"
(format-time-string "%A %a") ; "Tuesday 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

Documentation of format-time-string

Call describe-function to see the inline doc of format-time-string.

(info "(elisp) Time Parsing")

blog comments powered by Disqus