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