2

For creating Zim wiki pages, I need to generate a timestamp that ends with a time zone in ±hh:mm format. format-time-string has a %z format string that can insert it without the colon. Right now I use with-temp-buffer to generate the timestamp using %z, moving point back two characters and inserting a colon. My question is, is there a more sophisticated way to do this?

4

I'm afraid Emacs is rubbish at string manipulation, which is pretty amazing since Emacs is a text editor. It may not be awesome, but personally feel this reads better than using with-temp-buffer.

(let ((time (format-time-string "%z")))
  (concat
    (substring time 0 3)
    ":"
    (substring time 3)))
  • 1
    This feels a bit better for me than @kaushalmodi's regex solution. I actually generalized this in an insert-string-to-string defun. – GergelyPolonkai Feb 16 '15 at 18:45
  • 1
    I think Emacs is actually great for string manipulation, provided you use the buffer type and not the string type. ;-) – mbork Feb 16 '15 at 22:23
  • 1
    I agree, but using a buffer to manipulate a 6 characters long string sounds a bit like overkill to me… – GergelyPolonkai Feb 18 '15 at 12:45
4

If you like to use elisp regexp, you can do the below.

For example, it returns "-05:00" if (format-time-string "%z") returns "-0500".

(replace-regexp-in-string "\\([-+][0-9]\\{2\\}\\)\\([0-9]\\{2\\}\\)"
                          "\\1:\\2"
                          (format-time-string "%z"))
  • Sigh... if only Emacs supported PCRE or something similar without extensions... +1 anyway for the more general text manipulation idea. – PythonNut Feb 16 '15 at 18:38
4

A slightly less verbose version of the one suggested by kaushalmodi:

(replace-regexp-in-string "..$" ":\\&" (format-time-string "%z"))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.