Inserting Today’s Date

Ben Maughan over at Pragmatic Emacs posted a nice little bit of Elisp to insert today’s date. That reminded me that the first Elisp, other than routine configuration lines, that I wrote was a function to insert the date. Mine was a bit different in that two of the options involve the time. Just for the record, here it is

(defun jcs-datetime (arg)
  "Without argument: insert date as yyyy-mm-dd
With C-u: insert time
With C-u C-u: insert date and time"
  (interactive "P")
  (cond ((equal arg '(4)) (insert (format-time-string "%T")))
        ((equal arg '(16)) (insert (format-time-string "%Y-%m-%d %T")))
        (t (insert (format-time-string "%Y-%m-%d")))))

(global-set-key (kbd "C-c d") 'jcs-datetime)

Without any arguments, it acts just like Maughan’s function. With one universal argument it inserts just the time. With two universal arguments it inserts the date and time. I always want my dates to be Year-Month-Day so I don’t have a %d-%m-%Y option, like Maughan.

If, like me, you tend to do most of your work from Emacs, this is a tremendously useful thing. It seems like I’m always wanting to insert a date and the above function makes it easy. Looking at the code and my current workflow, it would probably make sense to switch the first two options so that a single universal argument gives the date and time and a double universal argument gives just the time but it’s been this way for a long time and is burnt into my muscle memory so I’ll probably just leave it the way it is.

This entry was posted in General and tagged . Bookmark the permalink.