How can I insert current date and time into a file using Emacs?
Solution 1:
C-u M-! date
Solution 2:
Put in your .emacs file:
;; ====================
;; insert date and time
(defvar current-date-time-format "%a %b %d %H:%M:%S %Z %Y"
"Format of date to insert with `insert-current-date-time' func
See help of `format-time-string' for possible replacements")
(defvar current-time-format "%a %H:%M:%S"
"Format of date to insert with `insert-current-time' func.
Note the weekly scope of the command's precision.")
(defun insert-current-date-time ()
"insert the current date and time into current buffer.
Uses `current-date-time-format' for the formatting the date/time."
(interactive)
(insert "==========\n")
; (insert (let () (comment-start)))
(insert (format-time-string current-date-time-format (current-time)))
(insert "\n")
)
(defun insert-current-time ()
"insert the current time (1-week scope) into the current buffer."
(interactive)
(insert (format-time-string current-time-format (current-time)))
(insert "\n")
)
(global-set-key "\C-c\C-d" 'insert-current-date-time)
(global-set-key "\C-c\C-t" 'insert-current-time)
Reference
Solution 3:
I've used these short snippets:
(defun now ()
"Insert string for the current time formatted like '2:34 PM'."
(interactive) ; permit invocation in minibuffer
(insert (format-time-string "%D %-I:%M %p")))
(defun today ()
"Insert string for today's date nicely formatted in American style,
e.g. Sunday, September 17, 2000."
(interactive) ; permit invocation in minibuffer
(insert (format-time-string "%A, %B %e, %Y")))
They originally came from journal.el
Solution 4:
For insert date:
M-x org-time-stamp
For insert date time:
C-u M-x org-time-stamp
You may bind a global key for this command.
org-mode
's method is very user friendly, you can select any date from calendar.
Solution 5:
You can install yasnippet, which will let you type "time" and the tab key, and does a whole lot more besides. It just calls current-time-string
behind the scenes, so you can control the formatting using format-time-string
.