Skip to content

Instantly share code, notes, and snippets.

@colonelpanic8
Created August 27, 2023 04:32
Show Gist options
  • Select an option

  • Save colonelpanic8/1387c03a4a42c005fbe11215a5e7b5d0 to your computer and use it in GitHub Desktop.

Select an option

Save colonelpanic8/1387c03a4a42c005fbe11215a5e7b5d0 to your computer and use it in GitHub Desktop.
(defun org-window-habit-normalize-time-to-duration (time-value &optional duration-plist)
(let* ((decoded-time (decode-time time-value))
(year (nth 5 decoded-time))
(month (nth 4 decoded-time))
(day (nth 3 decoded-time))
(hour (nth 2 decoded-time))
(minute (nth 1 decoded-time))
(second (nth 0 decoded-time))
(smallest-duration-type (car (last duration-plist 2)))
(smallest-duration-value (cadr (last duration-plist 2))))
;; Align time based on the smallest duration type and its value
(cond
((eq smallest-duration-type :seconds)
(encode-time (* smallest-duration-value (floor second smallest-duration-value)) minute hour day month year))
((eq smallest-duration-type :minutes)
(encode-time 0 (* smallest-duration-value (floor minute smallest-duration-value)) hour day month year))
((eq smallest-duration-type :hours)
;; Align to the start of the day for hours
(encode-time 0 0 (* smallest-duration-value (floor hour smallest-duration-value)) day month year))
((eq smallest-duration-type :days)
;; Go back by the duration value from the current day and align to that day at midnight.
(let* ((aligned-day (- day (1- smallest-duration-value)))) ; Subtracting one less than the duration to include the current day in the span.
(encode-time 0 0 0 aligned-day month year)))
((eq smallest-duration-type :months)
;; Months align to the start of the year
(encode-time 0 0 0 1 (* smallest-duration-value (floor month smallest-duration-value)) year))
((eq smallest-duration-type :years)
;; Go back by the duration value from the current year and align to January 1 of that year.
(let* ((aligned-year (- year (1- smallest-duration-value)))) ; Subtracting one less than the duration to include the current year in the span.
(encode-time 0 0 0 1 1 aligned-year)))
(t time-value))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment