3

How can you convert between ISO year-week-day and an elisp date that can be sent to, e.g., format-time-string? I do not want to go via a string representation.

I found the following old question on stackoverflow: https://stackoverflow.com/questions/20055504/iso-emacs-elisp-to-determines-dates-corresponding-to-first-last-days-of-a-week/, but haven't been able to find a published answer.

  • What is normal date? 31/03/1978, 31 Марта 1978 года, 03/31/1978, 31 de marzo de 1978? – Maxim Kim Aug 7 '18 at 7:06
  • I clarified what I mean with a "normal date". – Niclas Börlin Aug 8 '18 at 6:35
4

Base on your own answer, here is another way to do it.

(require 'cal-iso)

(defun iso-week-to-time (year week day)
  (pcase-let ((`(,m ,d ,y)
               (calendar-gregorian-from-absolute
                (calendar-iso-to-absolute (list week day year)))))
    (encode-time 0 0 0 d m y)))

(format-time-string "%F" (iso-week-to-time 2018 32 2))
;; => "2018-08-07"
1

Below is my own solution to the question.

calendar-iso-to-absolute and calendar-gregorian-from absolute converts the list (year week weekday) to the list (month day year) which is transformed to (0 0 0 day month year) and processed by encode-time. The result is an elisp time value that can be processed by format-time.

Example:

(format-time-string "%F" (iso-week-to-time 2018 32 1)) % Monday week 32 in 2018
"2018-08-06"

There should be simpler solutions as this is a kludge, especially the permutation of the list.

(defun iso-week-to-time(year week day)
  "Convert ISO year, week, day to elisp time value."
  (apply #'encode-time
         (append '(0 0 0)
                 (-select-by-indices
                  '(1 0 2)
                  (calendar-gregorian-from-absolute (calendar-iso-to-absolute
                                                     (list week day year)))))))

(defun iso-beginning-of-week(year week)
  "Convert ISO year, week to elisp time for first day (Monday) of week."
  (iso-week-to-time year week 1))

(defun iso-end-of-week(year week)
  "Convert ISO year, week to elisp time for last day (Sunday) of week."
  (iso-week-to-time year week 7))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.