Insert whole month of dates in Emacs Lisp

对着背影说爱祢 提交于 2019-12-08 19:19:05

问题


I'm doing a bit of programming here and there in Emacs Lisp, but I'm not entirely sure how to go about certain things.

I'm trying to insert a whole month of dates, each on a new line like the list below:

January

01/01/09 Mon:

02/01/09 Tue:

03/01/09 Wed:

etc

How would I go about doing that? I've found how to format dates, but I can't find how to loop over a certain range of dates (in this instance to loop round a whole month and print a date for each day in the month).

Has anyone got some pointers they could give me on how to get started?


回答1:


The functions you want are 'encode-time, 'format-time-string, and 'decode-time. For the proper documentation, either C-h f function-name or will give you the documentation for the function, or the general elisp info pages can be found here: C-h i m elisp RET m time conversion RET

Here's that snippet:

(defun my-insert-dates ()
  "insert a bunch of dates"
  (interactive)
  (let* ((month 3)
         (day 1)
         (time (encode-time 1 1 0 day month 2009)))
    (while (= (nth 4 (decode-time time)) month)
      (insert (format-time-string "%D %a:\n" time))
      (setq day (1+ day))
      (setq time (encode-time 1 1 0 day month 2009)))))

I couldn't find how to determine the number of days in a given month (sure, you could hard-code it, but then you've got to deal with leap years). Luckily, 'encode-time does all the addition for you, so if you pass it the equivalent of "February 31", it'll return "March 3" (assuming 28 days).




回答2:


I would have done something like this, if you don't mind using the calendar feature...

(require 'calendar)
(defun display-a-month (day month year)
  (insert (format "%s\n" (calendar-date-string (list  month day year))))
  (if (< day 30)
    (display-a-month (+ day 1) month year)))

You can find help using describe-function (M-x describe-function or C-h f as said before); M-x apropos will give you a list of functions related to something and even better people on irc.freenode.org / #emacs will answer all you questions.

btw, the question was "insert a whole month" not "insert first day of each month" :) depends if you read dd/mm/yyyy of mm/dd/yyyy




回答3:


Slight variation on Trey's answer using dotimes:

(defun my-insert-dates ()
  "insert the first day of each month"
  (interactive)
  (dotimes (mo 12)
    (insert (format-time-string "%D %a:\n" (encode-time 1 1 0 1 (1+ mo) 2009)))))


来源:https://stackoverflow.com/questions/753248/insert-whole-month-of-dates-in-emacs-lisp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!