Gnus -- Minor tweak define #'time-to-seconds
[packages] / xemacs-packages / calendar / cal-dst.el
1 ;;; cal-dst.el --- calendar functions for daylight saving rules
2
3 ;; Copyright (C) 1993, 1994, 1995, 1996, 2001, 2002, 2003, 2004, 2005,
4 ;;   2006, 2007  Free Software Foundation, Inc.
5
6 ;; Author: Paul Eggert <eggert@twinsun.com>
7 ;;      Edward M. Reingold <reingold@cs.uiuc.edu>
8 ;; Maintainer: Glenn Morris <rgm@gnu.org>
9 ;; Keywords: calendar
10 ;; Human-Keywords: daylight saving time, calendar, diary, holidays
11
12 ;; This file is part of XEmacs.
13
14 ;; XEmacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18
19 ;; XEmacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with XEmacs; see the file COPYING.  If not, write to the
26 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
27 ;; Boston, MA 02110-1301, USA.
28
29 ;;; Synched up with: FSF Emacs 22 CVS 2007-03-30
30
31 ;;; Commentary:
32
33 ;; This collection of functions implements the features of calendar.el and
34 ;; holiday.el that deal with daylight saving time.
35
36 ;; Comments, corrections, and improvements should be sent to
37 ;;  Edward M. Reingold               Department of Computer Science
38 ;;  (217) 333-6733                   University of Illinois at Urbana-Champaign
39 ;;  reingold@cs.uiuc.edu             1304 West Springfield Avenue
40 ;;                                   Urbana, Illinois 61801
41
42 ;;; Code:
43
44 (require 'calendar)
45 (require 'cal-persia)
46
47 (defcustom calendar-dst-check-each-year-flag t
48   "Non-nil means to check each year for DST transitions as needed.
49 Otherwise assume the next two transitions found after the
50 current date apply to all years.  This is faster, but not always
51 correct, since the dates of daylight saving transitions sometimes
52 change."
53   :type 'boolean
54   :version "22.1"
55   :group 'calendar)
56
57 (defvar calendar-current-time-zone-cache nil
58   "Cache for result of `calendar-current-time-zone'.")
59 (put 'calendar-current-time-zone-cache 'risky-local-variable t)
60
61 (defvar calendar-system-time-basis
62   (calendar-absolute-from-gregorian '(1 1 1970))
63   "Absolute date of starting date of system clock.")
64
65 (defun calendar-absolute-from-time (x utc-diff)
66   "Absolute local date of time X; local time is UTC-DIFF seconds from UTC.
67
68 X is (HIGH . LOW) or (HIGH LOW . IGNORED) where HIGH and LOW are the
69 high and low 16 bits, respectively, of the number of seconds since
70 1970-01-01 00:00:00 UTC, ignoring leap seconds.
71
72 Returns the pair (ABS-DATE . SECONDS) where SECONDS after local midnight on
73 absolute date ABS-DATE is the equivalent moment to X."
74   (let* ((h (car x))
75          (xtail (cdr x))
76          (l (+ utc-diff (if (numberp xtail) xtail (car xtail))))
77          (u (+ (* 512 (mod h 675)) (floor l 128))))
78     ;; Overflow is a terrible thing!
79     (cons (+ calendar-system-time-basis
80              ;; floor((2^16 h +l) / (60*60*24))
81              (* 512 (floor h 675)) (floor u 675))
82           ;; (2^16 h +l) mod (60*60*24)
83           (+ (* (mod u 675) 128) (mod l 128)))))
84
85 (defun calendar-time-from-absolute (abs-date s)
86   "Time of absolute date ABS-DATE, S seconds after midnight.
87
88 Returns the list (HIGH LOW) where HIGH and LOW are the high and low
89 16 bits, respectively, of the number of seconds 1970-01-01 00:00:00 UTC,
90 ignoring leap seconds, that is the equivalent moment to S seconds after
91 midnight UTC on absolute date ABS-DATE."
92   (let* ((a (- abs-date calendar-system-time-basis))
93          (u (+ (* 163 (mod a 512)) (floor s 128))))
94     ;; Overflow is a terrible thing!
95     (list
96      ;; floor((60*60*24*a + s) / 2^16)
97      (+ a (* 163 (floor a 512)) (floor u 512))
98      ;; (60*60*24*a + s) mod 2^16
99      (+ (* 128 (mod u 512)) (mod s 128)))))
100
101 (defun calendar-next-time-zone-transition (time)
102   "Return the time of the next time zone transition after TIME.
103 Both TIME and the result are acceptable arguments to current-time-zone.
104 Return nil if no such transition can be found."
105   (let* ((base 65536);; 2^16 = base of current-time output
106          (quarter-multiple 120);; approx = (seconds per quarter year) / base
107          (time-zone (current-time-zone time))
108          (time-utc-diff (car time-zone))
109          hi
110          hi-zone
111          (hi-utc-diff time-utc-diff)
112          (quarters '(2 1 3)))
113     ;; Heuristic: probe the time zone offset in the next three calendar
114     ;; quarters, looking for a time zone offset different from TIME.
115     (while (and quarters (eq time-utc-diff hi-utc-diff))
116       (setq hi (cons (+ (car time) (* (car quarters) quarter-multiple)) 0))
117       (setq hi-zone (current-time-zone hi))
118       (setq hi-utc-diff (car hi-zone))
119       (setq quarters (cdr quarters)))
120     (and
121      time-utc-diff
122      hi-utc-diff
123      (not (eq time-utc-diff hi-utc-diff))
124      ;; Now HI is after the next time zone transition.
125      ;; Set LO to TIME, and then binary search to increase LO and decrease HI
126      ;; until LO is just before and HI is just after the time zone transition.
127      (let* ((tail (cdr time))
128             (lo (cons (car time) (if (numberp tail) tail (car tail))))
129             probe)
130        (while
131            ;; Set PROBE to halfway between LO and HI, rounding down.
132            ;; If PROBE equals LO, we are done.
133            (let* ((lsum (+ (cdr lo) (cdr hi)))
134                   (hsum (+ (car lo) (car hi) (/ lsum base)))
135                   (hsumodd (logand 1 hsum)))
136              (setq probe (cons (/ (- hsum hsumodd) 2)
137                                (/ (+ (* hsumodd base) (% lsum base)) 2)))
138              (not (equal lo probe)))
139          ;; Set either LO or HI to PROBE, depending on probe results.
140          (if (eq (car (current-time-zone probe)) hi-utc-diff)
141              (setq hi probe)
142            (setq lo probe)))
143        hi))))
144
145 (defun calendar-time-zone-daylight-rules (abs-date utc-diff)
146   "Return daylight transition rule for ABS-DATE, UTC-DIFF sec offset from UTC.
147 ABS-DATE must specify a day that contains a daylight saving transition.
148 The result has the proper form for `calendar-daylight-savings-starts'."
149   (let* ((date (calendar-gregorian-from-absolute abs-date))
150          (weekday (% abs-date 7))
151          (m (extract-calendar-month date))
152          (d (extract-calendar-day date))
153          (y (extract-calendar-year date))
154          (last (calendar-last-day-of-month m y))
155          (candidate-rules
156           (append
157            ;; Day D of month M.
158            (list (list 'list m d 'year))
159            ;; The first WEEKDAY of month M.
160            (if (< d 8)
161                (list (list 'calendar-nth-named-day 1 weekday m 'year)))
162            ;; The last WEEKDAY of month M.
163            (if (> d (- last 7))
164                (list (list 'calendar-nth-named-day -1 weekday m 'year)))
165            ;; The first WEEKDAY after day J of month M, for D-6 < J <= D.
166            (let (l)
167              (calendar-for-loop j from (max 2 (- d 6)) to (min d (- last 8)) do
168                 (setq l
169                       (cons
170                        (list 'calendar-nth-named-day 1 weekday m 'year j)
171                        l)))
172              l)
173            ;; 01-01 and 07-01 for this year's Persian calendar.
174            (if (and (= m 3) (<= 20 d) (<= d 21))
175                '((calendar-gregorian-from-absolute
176                   (calendar-absolute-from-persian
177                    (list 1 1 (- year 621))))))
178            (if (and (= m 9) (<= 22 d) (<= d 23))
179                '((calendar-gregorian-from-absolute
180                   (calendar-absolute-from-persian
181                    (list 7 1 (- year 621))))))))
182          (prevday-sec (- -1 utc-diff)) ;; last sec of previous local day
183          (year (1+ y)))
184     ;; Scan through the next few years until only one rule remains.
185     (while
186         (let ((rules candidate-rules)
187               new-rules)
188           (while
189               (let*
190                   ((rule (car rules))
191                    (date
192                     ;; The following is much faster than
193                     ;; (calendar-absolute-from-gregorian (eval rule)).
194                     (cond ((eq (car rule) 'calendar-nth-named-day)
195                            (eval (cons 'calendar-nth-named-absday (cdr rule))))
196                           ((eq (car rule) 'calendar-gregorian-from-absolute)
197                            (eval (car (cdr rule))))
198                           (t (let ((g (eval rule)))
199                                (calendar-absolute-from-gregorian g))))))
200                 (or (equal
201                      (current-time-zone
202                       (calendar-time-from-absolute date prevday-sec))
203                      (current-time-zone
204                       (calendar-time-from-absolute (1+ date) prevday-sec)))
205                     (setq new-rules (cons rule new-rules)))
206                 (setq rules (cdr rules))))
207           ;; If no rules remain, just use the first candidate rule;
208           ;; it's wrong in general, but it's right for at least one year.
209           (setq candidate-rules (if new-rules (nreverse new-rules)
210                                   (list (car candidate-rules))))
211           (setq year (1+ year))
212           (cdr candidate-rules)))
213     (car candidate-rules)))
214
215 ;; TODO it might be better to extract this information directly from
216 ;; the system timezone database. But cross-platform...?
217 ;; See thread
218 ;; http://lists.gnu.org/archive/html/emacs-pretest-bug/2006-11/msg00060.html
219 (defun calendar-dst-find-data (&optional time)
220   "Find data on the first daylight saving time transitions after TIME.
221 TIME defaults to `current-time'.  Return value is as described
222 for `calendar-current-time-zone'."
223   (let* ((t0 (or time (current-time)))
224          (t0-zone (current-time-zone t0))
225          (t0-utc-diff (car t0-zone))
226          (t0-name (car (cdr t0-zone))))
227     (if (not t0-utc-diff)
228         ;; Little or no time zone information is available.
229         (list nil nil t0-name t0-name nil nil nil nil)
230       (let* ((t1 (calendar-next-time-zone-transition t0))
231              (t2 (and t1 (calendar-next-time-zone-transition t1))))
232         (if (not t2)
233             ;; This locale does not have daylight saving time.
234             (list (/ t0-utc-diff 60) 0 t0-name t0-name nil nil 0 0)
235           ;; Use heuristics to find daylight saving parameters.
236           (let* ((t1-zone (current-time-zone t1))
237                  (t1-utc-diff (car t1-zone))
238                  (t1-name (car (cdr t1-zone)))
239                  (t1-date-sec (calendar-absolute-from-time t1 t0-utc-diff))
240                  (t2-date-sec (calendar-absolute-from-time t2 t1-utc-diff))
241                  ;; TODO When calendar-dst-check-each-year-flag is non-nil,
242                  ;; the rules can be simpler than they currently are.
243                  (t1-rules (calendar-time-zone-daylight-rules
244                             (car t1-date-sec) t0-utc-diff))
245                  (t2-rules (calendar-time-zone-daylight-rules
246                             (car t2-date-sec) t1-utc-diff))
247                  (t1-time (/ (cdr t1-date-sec) 60))
248                  (t2-time (/ (cdr t2-date-sec) 60)))
249             (cons
250              (/ (min t0-utc-diff t1-utc-diff) 60)
251              (cons
252               (/ (abs (- t0-utc-diff t1-utc-diff)) 60)
253               (if (< t0-utc-diff t1-utc-diff)
254                   (list t0-name t1-name t1-rules t2-rules t1-time t2-time)
255                 (list t1-name t0-name t2-rules t1-rules t2-time t1-time)
256                 )))))))))
257
258 (defvar calendar-dst-transition-cache nil
259   "Internal cal-dst variable storing date of daylight saving time transitions.
260 Value is a list with elements of the form (YEAR START END), where
261 START and END are expressions that when evaluated return the
262 start and end dates (respectively) for DST in YEAR. Used by the
263 function `calendar-dst-find-startend'.")
264
265 (defun calendar-dst-find-startend (year)
266   "Find the dates in YEAR on which daylight saving time starts and ends.
267 Returns a list (YEAR START END), where START and END are
268 expressions that when evaluated return the start and end dates,
269 respectively. This function first attempts to use pre-calculated
270 data from `calendar-dst-transition-cache', otherwise it calls
271 `calendar-dst-find-data' (and adds the results to the cache)."
272   (let ((e (assoc year calendar-dst-transition-cache))
273         f)
274     (or e
275         (progn
276           (setq e (calendar-dst-find-data (encode-time 1 0 0 1 1 year))
277                 f (nth 4 e)
278                 e (list year f (nth 5 e))
279                 calendar-dst-transition-cache
280                 (append calendar-dst-transition-cache (list e)))
281           e))))
282
283 (defun calendar-current-time-zone ()
284   "Return UTC difference, dst offset, names and rules for current time zone.
285
286 Returns (UTC-DIFF DST-OFFSET STD-ZONE DST-ZONE DST-STARTS DST-ENDS
287 DST-STARTS-TIME DST-ENDS-TIME), based on a heuristic probing of what the
288 system knows:
289
290 UTC-DIFF is an integer specifying the number of minutes difference between
291     standard time in the current time zone and Coordinated Universal Time
292     (Greenwich Mean Time).  A negative value means west of Greenwich.
293 DST-OFFSET is an integer giving the daylight saving time offset in minutes.
294 STD-ZONE is a string giving the name of the time zone when no seasonal time
295     adjustment is in effect.
296 DST-ZONE is a string giving the name of the time zone when there is a seasonal
297     time adjustment in effect.
298 DST-STARTS and DST-ENDS are sexps in the variable `year' giving the daylight
299     saving time start and end rules, in the form expected by
300     `calendar-daylight-savings-starts'.
301 DST-STARTS-TIME and DST-ENDS-TIME are integers giving the number of minutes
302     after midnight that daylight saving time starts and ends.
303
304 If the local area does not use a seasonal time adjustment, STD-ZONE and
305 DST-ZONE are equal, and all the DST-* integer variables are 0.
306
307 Some operating systems cannot provide all this information to Emacs; in this
308 case, `calendar-current-time-zone' returns a list containing nil for the data
309 it can't find."
310   (unless calendar-current-time-zone-cache
311     (setq calendar-current-time-zone-cache (calendar-dst-find-data))))
312
313 ;;; The following eight defvars relating to daylight saving time should NOT be
314 ;;; marked to go into loaddefs.el where they would be evaluated when Emacs is
315 ;;; dumped.  These variables' appropriate values depend on the conditions under
316 ;;; which the code is INVOKED; so it's inappropriate to initialize them when
317 ;;; Emacs is dumped---they should be initialized when calendar.el is loaded.
318 ;;; They default to US Eastern time if time zone info is not available.
319
320 (calendar-current-time-zone)
321
322 (defvar calendar-time-zone (or (car calendar-current-time-zone-cache) -300)
323   "*Number of minutes difference between local standard time at
324 `calendar-location-name' and Coordinated Universal (Greenwich) Time.  For
325 example, -300 for New York City, -480 for Los Angeles.")
326
327 (defvar calendar-daylight-time-offset
328   (or (car (cdr calendar-current-time-zone-cache)) 60)
329   "*Number of minutes difference between daylight saving and standard time.
330
331 If the locale never uses daylight saving time, set this to 0.")
332
333 (defvar calendar-standard-time-zone-name
334   (or (car (nthcdr 2 calendar-current-time-zone-cache)) "EST")
335   "*Abbreviated name of standard time zone at `calendar-location-name'.
336 For example, \"EST\" in New York City, \"PST\" for Los Angeles.")
337
338 (defvar calendar-daylight-time-zone-name
339   (or (car (nthcdr 3 calendar-current-time-zone-cache)) "EDT")
340   "*Abbreviated name of daylight saving time zone at `calendar-location-name'.
341 For example, \"EDT\" in New York City, \"PDT\" for Los Angeles.")
342
343
344 (defun calendar-dst-starts (year)
345   "Return the date of YEAR on which daylight saving time starts.
346 This function respects the value of `calendar-dst-check-each-year-flag'."
347   (or (let ((expr (if calendar-dst-check-each-year-flag
348                       (cadr (calendar-dst-find-startend year))
349                     (nth 4 calendar-current-time-zone-cache))))
350         (if expr (eval expr)))
351       ;; New US rules commencing 2007.  ftp://elsie.nci.nih.gov/pub/.
352       (and (not (zerop calendar-daylight-time-offset))
353            (calendar-nth-named-day 2 0 3 year))))
354
355 (defun calendar-dst-ends (year)
356   "Return the date of YEAR on which daylight saving time ends.
357 This function respects the value of `calendar-dst-check-each-year-flag'."
358   (or (let ((expr (if calendar-dst-check-each-year-flag
359                       (nth 2 (calendar-dst-find-startend year))
360                     (nth 5 calendar-current-time-zone-cache))))
361         (if expr (eval expr)))
362       ;; New US rules commencing 2007.  ftp://elsie.nci.nih.gov/pub/.
363       (and (not (zerop calendar-daylight-time-offset))
364            (calendar-nth-named-day 1 0 11 year))))
365
366
367 ;;;###autoload
368 (put 'calendar-daylight-savings-starts 'risky-local-variable t)
369 (defvar calendar-daylight-savings-starts
370   '(calendar-dst-starts year)
371   "*Sexp giving the date on which daylight saving time starts.
372 This is an expression in the variable `year' whose value gives the Gregorian
373 date in the form (month day year) on which daylight saving time starts.  It is
374 used to determine the starting date of daylight saving time for the holiday
375 list and for correcting times of day in the solar and lunar calculations.
376
377 For example, if daylight saving time is mandated to start on October 1,
378 you would set `calendar-daylight-savings-starts' to
379
380       '(10 1 year)
381
382 If it starts on the first Sunday in April, you would set it to
383
384       '(calendar-nth-named-day 1 0 4 year)
385
386 If the locale never uses daylight saving time, set this to nil.")
387
388 ;;;###autoload
389 (put 'calendar-daylight-savings-ends 'risky-local-variable t)
390 (defvar calendar-daylight-savings-ends
391   '(calendar-dst-ends year)
392   "*Sexp giving the date on which daylight saving time ends.
393 This is an expression in the variable `year' whose value gives the Gregorian
394 date in the form (month day year) on which daylight saving time ends.  It is
395 used to determine the starting date of daylight saving time for the holiday
396 list and for correcting times of day in the solar and lunar calculations.
397
398 For example, if daylight saving time ends on the last Sunday in October:
399
400       '(calendar-nth-named-day -1 0 10 year)
401
402 If the locale never uses daylight saving time, set this to nil.")
403
404 (defvar calendar-daylight-savings-starts-time
405   (or (car (nthcdr 6 calendar-current-time-zone-cache)) 120)
406   "*Number of minutes after midnight that daylight saving time starts.")
407
408 (defvar calendar-daylight-savings-ends-time
409   (or (car (nthcdr 7 calendar-current-time-zone-cache))
410       calendar-daylight-savings-starts-time)
411   "*Number of minutes after midnight that daylight saving time ends.")
412
413 (defun dst-in-effect (date)
414   "True if on absolute DATE daylight saving time is in effect.
415 Fractional part of DATE is local standard time of day."
416   (let* ((year (extract-calendar-year
417                 (calendar-gregorian-from-absolute (floor date))))
418          (dst-starts-gregorian (eval calendar-daylight-savings-starts))
419          (dst-ends-gregorian (eval calendar-daylight-savings-ends))
420          (dst-starts (and dst-starts-gregorian
421                           (+ (calendar-absolute-from-gregorian
422                               dst-starts-gregorian)
423                              (/ calendar-daylight-savings-starts-time
424                                 60.0 24.0))))
425          (dst-ends (and dst-ends-gregorian
426                         (+ (calendar-absolute-from-gregorian
427                             dst-ends-gregorian)
428                            (/ (- calendar-daylight-savings-ends-time
429                                  calendar-daylight-time-offset)
430                               60.0 24.0)))))
431     (and dst-starts dst-ends
432          (if (< dst-starts dst-ends)
433              (and (<= dst-starts date) (< date dst-ends))
434            (or (<= dst-starts date) (< date dst-ends))))))
435
436 (defun dst-adjust-time (date time &optional style)
437   "Adjust, to account for dst on DATE, decimal fraction standard TIME.
438 Returns a list (date adj-time zone) where `date' and `adj-time' are the values
439 adjusted for `zone'; here `date' is a list (month day year), `adj-time' is a
440 decimal fraction time, and `zone' is a string.
441
442 Optional parameter STYLE forces the result time to be standard time when its
443 value is 'standard and daylight saving time (if available) when its value is
444 'daylight.
445
446 Conversion to daylight saving time is done according to
447 `calendar-daylight-savings-starts', `calendar-daylight-savings-ends',
448 `calendar-daylight-savings-starts-time',
449 `calendar-daylight-savings-ends-time', and
450 `calendar-daylight-savings-offset'."
451
452   (let* ((rounded-abs-date (+ (calendar-absolute-from-gregorian date)
453                               (/ (round (* 60 time)) 60.0 24.0)))
454          (dst (dst-in-effect rounded-abs-date))
455          (time-zone (if dst
456                         calendar-daylight-time-zone-name
457                         calendar-standard-time-zone-name))
458          (time (+ rounded-abs-date
459                   (if dst (/ calendar-daylight-time-offset 24.0 60.0) 0))))
460     (list (calendar-gregorian-from-absolute (truncate time))
461           (* 24.0 (- time (truncate time)))
462           time-zone)))
463
464 (provide 'cal-dst)
465
466 ;;; arch-tag: a141d204-213c-4ca5-bdc6-f9df3aa92aad
467 ;;; cal-dst.el ends here