robintw
robintw

Reputation: 28581

Insert whole month of dates in Emacs Lisp

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?

Upvotes: 7

Views: 1403

Answers (3)

Ben
Ben

Reputation: 7618

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

Upvotes: 4

Trey Jackson
Trey Jackson

Reputation: 74480

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).

Upvotes: 8

scottfrazer
scottfrazer

Reputation: 17327

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)))))

Upvotes: 2

Related Questions