【问题标题】:How can I add a format specifier to `format-time-string`?如何将格式说明符添加到“格式时间字符串”?
【发布时间】:2013-12-01 20:19:10
【问题描述】:

我有如下函数定义:

(defun nth (n)
  (format
   (concat
    "%d"
    (if (memq n '(11 12 13)) "th"
      (let ((last-digit (% n 10)))
        (case last-digit
          (1 "st")
          (2 "nd")
          (3 "rd")
          (otherwise "th"))))) n))

我希望能够在format-time-string 中使用它。 通常,我会查看函数的源代码,但这个函数是在 C 源代码中定义的。 (我认为这会阻止将某些东西挂在上面,但我会得到纠正。)

如何添加另一个格式说明符(例如,%o)以将nth 应用于适当的参数?

所需用途:

(format-time-string "%A, %B %o, %T (%z)" (seconds-to-time 1250553600))

=> "Monday, August 17th, 20:00:00 (-0400)"

【问题讨论】:

    标签: emacs elisp format-string


    【解决方案1】:

    这就是你想要做的。 Stefan 和 Drew 已经给出了一些重要的评论(不要覆盖 nth 并查看 emacs-lisp/advising 函数的信息文件)。

    (defun ordinal (n)
      "Special day of month format."
      (format
       (concat
        "%d"
        (if (memq n '(11 12 13)) "th"
          (let ((last-digit (% n 10)))
            (case last-digit
              (1 "st")
              (2 "nd")
              (3 "rd")
              (otherwise "th"))))) n))
    
    
    (defadvice format-time-string (before ordinal activate)
      "Add ordinal to %d."
      (let ((day (nth 3 (decode-time (or time (current-time))))))
        (setq format-string
          (replace-regexp-in-string "%o"
                        (ordinal day)
                        format-string))))
    

    注意事项:

    1. 我没有处理 UNIVERSAL 参数

    2. 当从 C 调用 format-time-string 时,该 hack 不起作用(您可以在手册中阅读)。

    【讨论】:

      【解决方案2】:

      AFAIK 你运气不好:format-time-string 不提供任何方法来做到这一点。

      您可以使用以下方法解决此问题:

      (let ((ti (seconds-to-time 1250553600)))
       (format-time-string (concat "%A, %B " (my-nth (format-time-string "%d" ti)) ", %T (%z)") ti))
      

      这就是说,我一直被告知“8 月 17 日”是错误的:你应该写“8 月 17 日”,发音为“8 月 17 日”。

      还有一点:nth 是一个预定义的核心函数。最好不要用你自己完全不同的定义覆盖它。

      【讨论】:

      • 完全忘记了内置的nth - 感谢您的提醒。您可能对“8 月 17 日”的看法是正确的,但我相信“8 月 17 日”在这种情况下是正确的。
      【解决方案3】:

      补充 Stefan 所说的话(“你不走运”)--

      format-time-string 是内置的,但您也可以advise 内置。但是,由于您想做的那种手术会深入到定义的深处(您不能这样做),您实际上需要替换 format-time-string 在@987654323 中的定义@,即根本不使用ad-do-it

      换句话说,无论哪种方式(defundefadvice),您都需要在 Lisp 中完全重新定义函数。这与说“你不走运”差不多。

      【讨论】:

        猜你喜欢
        • 2011-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-04
        • 1970-01-01
        • 2010-10-06
        相关资源
        最近更新 更多