Elisp: Parse Date Time

By Xah Lee. Date: . Last updated: .

This page shows you how to parse date time string.

Problem

Write a elisp function. The function will take a string argument that's any of common date time format, example

and output a canonical form 2011-09-02T11:14:11+0200.

Solution

Two builtin lib to parse datetime:

(parse-time-string STRING) return a list like this: (SEC MIN HOUR DAY MON YEAR DOW DST TZ)

any values that are unknown are returned as nil. in emacs 27, unknown DST value is returned as -1.

(iso8601-parse STRING &optional FORM) return the same format. iso8601-parse is designed for parsing ISO 1601 time formats.

Supported Formats of parse-time-string

;; testing what time formats parse-time-string supports
;; As of GNU Emacs 27.1 of 2020-08-11

(require 'parse-time)

;; parse-time-string returns
;; (SEC MIN HOUR DAY MON YEAR DOW DST TZ)
;; if a element is nil or -1, it means unknown

(parse-time-string "Date: Mon, 01 Aug 2011 12:24:51 -0400")
;; (51 24 12 1 8 2011 1 -1 -14400)
;; yes

(parse-time-string "Local: Mon, Aug 1 2011 9:24 am")
;; (0 24 9 1 8 2011 1 -1 nil)
;; yes

(parse-time-string "2007, August 1")
;; (nil nil nil 1 8 2007 nil -1 nil)
;; yes

(parse-time-string "August 1, 2007")
;; (nil nil nil 1 8 2007 nil -1 nil)
;; yes

(parse-time-string "august 1, 2007")
;; (nil nil nil 1 8 2007 nil -1 nil)
;; yes

(parse-time-string "August 1st, 2007")
;; (nil nil nil nil 8 2007 nil -1 nil)
;; no. The date is nil

(parse-time-string "aug 1, 2007")
(nil nil nil 1 8 2007 nil -1 nil)
;; yes

(parse-time-string "1 aug, 2007")
;; (nil nil nil 1 8 2007 nil -1 nil)
;; yes

(parse-time-string "8/1/2007")
;; (nil nil nil 8 nil 2001 nil -1 nil)
;; no. Takes the 8 as date, 1 as nil

(parse-time-string "08/01/2007")
;; (nil nil nil 8 nil 2001 nil -1 nil)
;; no. Takes the 8 as date, 1 as nil

(parse-time-string "8,1,2007")
(nil nil nil 8 nil 2001 nil -1 nil)
;; no

(parse-time-string "2007-08-01")
;; (nil nil nil 1 8 2007 nil -1 nil)
;; yes

(parse-time-string "2007")
;; (nil nil nil nil nil 2007 nil -1 nil)
;; yes

(parse-time-string "2007-08")
;; (nil nil nil nil nil nil nil -1 nil)
;; no

(parse-time-string "2011-08-01T11:55:37-07:00")
;; (nil nil nil nil nil nil nil -1 nil)
;; no

Datetime Parser Function

Elisp: xah-fix-datetime

Datetime

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys

ELisp

ELisp Examples

ELisp Write Major Mode


ELisp

Basics

Basic Functions

Writing Command

Writing Script

Lisp Data Structure

Lisp Symbol

Elisp Misc