tags:

views:

321

answers:

3

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?

+3  A: 

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

Trey Jackson
+1  A: 

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)))))
scottfrazer
Just commenting that I updated my answer to cycle through the days (not months). Just in case people got confused as to how you derived your answer from mine.
Trey Jackson
Ack, now my answer makes no sense :) Oh well, dotimes is still good to know about for counting loops.
scottfrazer
Yup, I forget about dotimes.
Trey Jackson
+3  A: 

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

Ben
Out of curiosity, why the `(let (_) ...` wrapper?
Trey Jackson
Just because a forgot that elisp was able to do non-functional work. updating ...
Ben