Insert all month dates in Emacs Lisp

I do a bit of programming here and there in Emacs Lisp, but I'm not quite sure how to go about some things.

I am trying to insert a whole month of dates, each on a new line, as shown below:

January

01/01/09 Mon:

02/01/09 W:

01/03/09 Wed:

etc.

How would I do that? I found how to format dates, but I can’t find how to iterate over a specific date range (in this case, the cycle is rounded off for a whole month and print the date for each day of the month).

Does anyone have some pointers that they can give me on how to get started?

+6
emacs elisp
source share
3 answers

The functions you want are 'encode-time , 'format-time-string and 'decode-time . For proper documentation, either Ch f function-name , or you will receive documentation for this function, or the general elisp information pages can be found here: Ch im elisp RET m time conversion RET

Here is this 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 could not find how to determine the number of days in a given month (of course, you can hard code it, but then you have to deal with leap years). Fortunately, 'encode-time makes the whole addition for you, so if you give it the equivalent of February 31, it will return March 3 (within 28 days).

+6
source share

I would do something like this if you don't mind using the calendar function ...

 (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 the descriptive function (Mx describe-function or Ch f, as mentioned earlier); Mx apropos will provide you with a list of features related to something, and even the best people at irc.freenode.org/#emacs will answer all your questions.

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

+3
source share

Minor change in Trey's answer using topims:

 (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))))) 
+1
source share

All Articles