4

(format-time-string "%p") is empty in my Emacs. How I can format date in AM/PM format?

That answer second part of Show time in different time zones

UPDATE

(length (format-time-string "%p"))  ; is 0
(getenv "LC_TIME")                  ; is "en_DK.utf8"

My default preferences (in .emacs):

(setq display-time-24hr-format t)
(setq display-time-day-and-date nil)
gavenkoa
  • 3,352
  • 19
  • 36
  • The documentation says that %p is the locale’s equivalent of either AM or PM. So I suspect the problem is with the `en_DK` locale on your machine. You could try the command `date +%p` in a terminal window. Does it match what you see in emacs? (Make sure that the locale matches when you test.) – Harald Hanche-Olsen Mar 08 '16 at 16:40

3 Answers3

2

format-time-string requires a format together with an actual time to format. So you want to write something like

(format-time-string "%p" (current-time))

which at the moment outputs am for me. Similarly

(format-time-string "%l:%M %p" (current-time))

currently gives 9:40 am.

Andrew Swann
  • 3,436
  • 2
  • 15
  • 43
2

According to Locales section in Elisp manual, the format-time-string function is influenced by the system locale configuration. Moreover, the function docstring says "%p is the locale’s equivalent of either AM or PM.".

Because of these tips, I wrote the following code to changed the locale temporarily before using the format function:

(let ((system-time-locale "en_US.UTF-8"))
  (format-time-string "%r %p" (current-time)))

After some tries at the scratch buffer, it seems that using the "en_US.UTF-8" locale prints the "PM"/"AM". These are the results after executing each sexp with C-j (eval-print-last-sexp):

(let ((system-time-locale "en_US.UTF-8"))
  (format-time-string "%r %p" (current-time)))
"01:21:33 PM PM"

(let ((system-time-locale "en_DK.UTF-8"))
  (format-time-string "%r %p" (current-time)))
"01:21:55  "

(let ((system-time-locale "en_UK.UTF-8"))
  (format-time-string "%r %p" (current-time)))
"01:22:14  "
cnngimenez
  • 21
  • 1
0

Inside the emacs manual there is this page: https://www.gnu.org/software/emacs/manual/html_node/emacs/Time-Display-Format.html. that talks about changing the time format.

The following code should do what you want if I understand correctly.

(setq display-time-24hr-format nil)
(setq display-time-string-forms
      '(12-hours ":" minutes am-pm))
Jules
  • 1,275
  • 7
  • 12
  • How your suggestion can be applied to `(format-time-string "%p")` without altering global settings? – gavenkoa Mar 07 '16 at 16:38
  • Well I guess I don't know exactly what you mean by it being empty. Would you be able to add something like this: `(format-time-string (concat "Start of string " (if (>= (string-to-number (substring (current-time-string (current-time)) 11 13)) 12) "PM" "AM") " end of string"))` – Jules Mar 07 '16 at 16:51