如何用Emacs Lisp对ISO8601日期字符串执行减一天操作?
Emacs Lisp日期转换问题:将"2020-06-01"转为"2020-05-31"
你提供的代码返回错误结果1999-12-30,问题出在time-subtract对内部时间格式的处理上——date-to-time返回带时区信息的内部时间结构,而days-to-time返回纯时间增量,二者直接相减在部分Emacs版本中会出现计算异常。
以下是两种可靠的解决方法:
方法一:通过时间组件修改日期
先将日期解码为时间组件,直接调整日份后重新编码:
(let* ((target-time (date-to-time "2020-06-01")) (time-components (decode-time target-time))) (format-time-string "%Y-%m-%d" (apply #'encode-time (append (butlast time-components 6) (list (- (nth 3 time-components) 1)) (nthcdr 4 time-components)))))
方法二:基于秒数的时间运算
将时间转换为从1970年开始的秒数,减去一天的秒数(86400)后再转回时间格式:
(format-time-string "%Y-%m-%d" (seconds-to-time (- (time-to-seconds (date-to-time "2020-06-01")) 86400)))
两种方法都能正确输出2020-05-31。
内容的提问来源于stack exchange,提问作者George Mauer
相关产品推荐
相关产品推荐

