InsertingTodaysDate

Last edit

Changed:

< (defun insert-current-date () (interactive)
< (insert (shell-command-to-string "echo -n $(date +%Y-%m-%d)")))

to

> (defun insert-current-date () (interactive)
> (insert (shell-command-to-string "echo -n $(date +%Y-%m-%d)")))


The following are ways to quickly insert the current date in things like articles, letters and other written documents.

See InsertingAndUpdatingDates for other ways to insert dates in buffers and files.

Using the Shell to Insert the Date

  (defun insert-current-date () (interactive)
    (insert (shell-command-to-string "echo -n $(date +%Y-%m-%d)")))

Or

 `C-u M-! date +"%B %e, %Y" RET'

Running this command will give something like:

 December  2, 2005

Using the Emacs Calendar

CalendarMode can determine the proper date format for your locale, therefore a command can be written for inserting today’s date. This method gives you the most control over the language and format. Change the calendar interpretation in Emacs--if you haven’t already--with `M-x calendar-set-date-style RET american or `M-x calendar-set-date-style european. Fine tune the date format by customizing ‘calendar-date-display-form’ variable with ‘M-x customize-variable’.

  (require 'calendar)
  (defun insdate-insert-current-date (&optional omit-day-of-week-p)
    "Insert today's date using the current locale.
  With a prefix argument, the date is inserted without the day of
  the week."
    (interactive "P*")
    (insert (calendar-date-string (calendar-current-date) nil
				  omit-day-of-week-p)))

You can run this command with ‘M-x insdate-insert-current-date’ or bind this command to ‘C-x M-d’:

  (global-set-key "\C-x\M-d" `insdate-insert-current-date)

See also a related useful command that can InsertAnyDate, by taking a numeric PrefixArgument to insert the date X days from the current date.

Using `format-time-string'

ClausBrunzema uses the following two commands to insert the variations of date formats (ISO and european formats).

 (defun date (arg)
   (interactive "P")
   (insert (if arg
               (format-time-string "%d.%m.%Y")
             (format-time-string "%Y-%m-%d"))))
 (defun timestamp ()
   (interactive)
   (insert (format-time-string "%Y-%m-%dT%H:%M:%S")))

The functionality of the above two commands are combined into a single command, InsertDate, by JorgenSchaefer.

There is a trade-off between simplicity and flexibility, and most solutions seem to favor simplicity over flexibility. Here is an attempt to support the user’s preference for different date and time formats while still minimizing keystrokes: Lisp:insert-time-string.el


CategoryCalendar CategoryEditing