Add 2011 to FSF/AIST copyright years.
[gnus] / lisp / time-date.el
1 ;;; time-date.el --- Date and time handling functions
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
4 ;;   2007, 2008, 2009, 2010, 2011  Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;;      Masanobu Umeda <umerin@mse.kyutech.ac.jp>
8 ;; Keywords: mail news util
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; Time values come in three formats.  The oldest format is a cons
28 ;; cell of the form (HIGH . LOW).  This format is obsolete, but still
29 ;; supported.  The two other formats are the lists (HIGH LOW) and
30 ;; (HIGH LOW MICRO).  The first two formats specify HIGH * 2^16 + LOW
31 ;; seconds; the third format specifies HIGH * 2^16 + LOW + MICRO /
32 ;; 1000000 seconds.  We should have 0 <= MICRO < 1000000 and 0 <= LOW
33 ;; < 2^16.  If the time value represents a point in time, then HIGH is
34 ;; nonnegative.  If the time value is a time difference, then HIGH can
35 ;; be negative as well.  The macro `with-decoded-time-value' and the
36 ;; function `encode-time-value' make it easier to deal with these
37 ;; three formats.  See `time-subtract' for an example of how to use
38 ;; them.
39
40 ;;; Code:
41
42 (defmacro with-decoded-time-value (varlist &rest body)
43   "Decode a time value and bind it according to VARLIST, then eval BODY.
44
45 The value of the last form in BODY is returned.
46
47 Each element of the list VARLIST is a list of the form
48 \(HIGH-SYMBOL LOW-SYMBOL MICRO-SYMBOL [TYPE-SYMBOL] TIME-VALUE).
49 The time value TIME-VALUE is decoded and the result it bound to
50 the symbols HIGH-SYMBOL, LOW-SYMBOL and MICRO-SYMBOL.
51
52 The optional TYPE-SYMBOL is bound to the type of the time value.
53 Type 0 is the cons cell (HIGH . LOW), type 1 is the list (HIGH
54 LOW), and type 2 is the list (HIGH LOW MICRO)."
55   (declare (indent 1)
56            (debug ((&rest (symbolp symbolp symbolp &or [symbolp form] form))
57                    body)))
58   (if varlist
59       (let* ((elt (pop varlist))
60              (high (pop elt))
61              (low (pop elt))
62              (micro (pop elt))
63              (type (unless (eq (length elt) 1)
64                      (pop elt)))
65              (time-value (car elt))
66              (gensym (make-symbol "time")))
67         `(let* ,(append `((,gensym ,time-value)
68                           (,high (pop ,gensym))
69                           ,low ,micro)
70                         (when type `(,type)))
71            (if (consp ,gensym)
72                (progn
73                  (setq ,low (pop ,gensym))
74                  (if ,gensym
75                      ,(append `(setq ,micro (car ,gensym))
76                               (when type `(,type 2)))
77                    ,(append `(setq ,micro 0)
78                             (when type `(,type 1)))))
79              ,(append `(setq ,low ,gensym ,micro 0)
80                       (when type `(,type 0))))
81            (with-decoded-time-value ,varlist ,@body)))
82     `(progn ,@body)))
83
84 (defun encode-time-value (high low micro type)
85   "Encode HIGH, LOW, and MICRO into a time value of type TYPE.
86 Type 0 is the cons cell (HIGH . LOW), type 1 is the list (HIGH LOW),
87 and type 2 is the list (HIGH LOW MICRO)."
88   (cond
89    ((eq type 0) (cons high low))
90    ((eq type 1) (list high low))
91    ((eq type 2) (list high low micro))))
92
93 (autoload 'parse-time-string "parse-time")
94 (autoload 'timezone-make-date-arpa-standard "timezone")
95
96 ;;;###autoload
97 ;; `parse-time-string' isn't sufficiently general or robust.  It fails
98 ;; to grok some of the formats that timezone does (e.g. dodgy
99 ;; post-2000 stuff from some Elms) and either fails or returns bogus
100 ;; values.  timezone-make-date-arpa-standard should help.
101 (defun date-to-time (date)
102   "Parse a string DATE that represents a date-time and return a time value.
103 If DATE lacks timezone information, GMT is assumed."
104   (condition-case ()
105       (apply 'encode-time (parse-time-string date))
106     (error (condition-case ()
107                (apply 'encode-time
108                       (parse-time-string
109                        (timezone-make-date-arpa-standard date)))
110              (error (error "Invalid date: %s" date))))))
111
112 ;; Bit of a mess.  Emacs has float-time since at least 21.1.
113 ;; This file is synced to Gnus, and XEmacs packages may have been written
114 ;; using time-to-seconds from the Gnus library.
115 ;;;###autoload(if (or (featurep 'emacs)
116 ;;;###autoload        (and (fboundp 'float-time)
117 ;;;###autoload             (subrp (symbol-function 'float-time))))
118 ;;;###autoload    (progn
119 ;;;###autoload      (defalias 'time-to-seconds 'float-time)
120 ;;;###autoload      (make-obsolete 'time-to-seconds 'float-time "21.1"))
121 ;;;###autoload  (autoload 'time-to-seconds "time-date"))
122
123 (eval-when-compile
124   (or (featurep 'emacs)
125       (and (fboundp 'float-time)
126            (subrp (symbol-function 'float-time)))
127       (defun time-to-seconds (time)
128         "Convert time value TIME to a floating point number."
129         (with-decoded-time-value ((high low micro time))
130           (+ (* 1.0 high 65536)
131              low
132              (/ micro 1000000.0))))))
133
134 ;;;###autoload
135 (defun seconds-to-time (seconds)
136   "Convert SECONDS (a floating point number) to a time value."
137   (list (floor seconds 65536)
138         (floor (mod seconds 65536))
139         (floor (* (- seconds (ffloor seconds)) 1000000))))
140
141 ;;;###autoload
142 (defun time-less-p (t1 t2)
143   "Return non-nil if time value T1 is earlier than time value T2."
144   (with-decoded-time-value ((high1 low1 micro1 t1)
145                             (high2 low2 micro2 t2))
146     (or (< high1 high2)
147         (and (= high1 high2)
148              (or (< low1 low2)
149                  (and (= low1 low2)
150                       (< micro1 micro2)))))))
151
152 ;;;###autoload
153 (defun days-to-time (days)
154   "Convert DAYS into a time value."
155   (let* ((seconds (* 1.0 days 60 60 24))
156          (high (condition-case nil (floor (/ seconds 65536))
157                  (range-error most-positive-fixnum))))
158     (list high (condition-case nil (floor (- seconds (* 1.0 high 65536)))
159                  (range-error 65535)))))
160
161 ;;;###autoload
162 (defun time-since (time)
163   "Return the time elapsed since TIME.
164 TIME should be either a time value or a date-time string."
165   (when (stringp time)
166     ;; Convert date strings to internal time.
167     (setq time (date-to-time time)))
168   (time-subtract (current-time) time))
169
170 ;;;###autoload
171 (defalias 'subtract-time 'time-subtract)
172
173 ;;;###autoload
174 (defun time-subtract (t1 t2)
175   "Subtract two time values, T1 minus T2.
176 Return the difference in the format of a time value."
177   (with-decoded-time-value ((high low micro type t1)
178                             (high2 low2 micro2 type2 t2))
179     (setq high (- high high2)
180           low (- low low2)
181           micro (- micro micro2)
182           type (max type type2))
183     (when (< micro 0)
184       (setq low (1- low)
185             micro (+ micro 1000000)))
186     (when (< low 0)
187       (setq high (1- high)
188             low (+ low 65536)))
189     (encode-time-value high low micro type)))
190
191 ;;;###autoload
192 (defun time-add (t1 t2)
193   "Add two time values T1 and T2.  One should represent a time difference."
194   (with-decoded-time-value ((high low micro type t1)
195                             (high2 low2 micro2 type2 t2))
196     (setq high (+ high high2)
197           low (+ low low2)
198           micro (+ micro micro2)
199           type (max type type2))
200     (when (>= micro 1000000)
201       (setq low (1+ low)
202             micro (- micro 1000000)))
203     (when (>= low 65536)
204       (setq high (1+ high)
205             low (- low 65536)))
206     (encode-time-value high low micro type)))
207
208 ;;;###autoload
209 (defun date-to-day (date)
210   "Return the number of days between year 1 and DATE.
211 DATE should be a date-time string."
212   (time-to-days (date-to-time date)))
213
214 ;;;###autoload
215 (defun days-between (date1 date2)
216   "Return the number of days between DATE1 and DATE2.
217 DATE1 and DATE2 should be date-time strings."
218   (- (date-to-day date1) (date-to-day date2)))
219
220 ;;;###autoload
221 (defun date-leap-year-p (year)
222   "Return t if YEAR is a leap year."
223   (or (and (zerop (% year 4))
224            (not (zerop (% year 100))))
225       (zerop (% year 400))))
226
227 ;;;###autoload
228 (defun time-to-day-in-year (time)
229   "Return the day number within the year corresponding to TIME."
230   (let* ((tim (decode-time time))
231          (month (nth 4 tim))
232          (day (nth 3 tim))
233          (year (nth 5 tim))
234          (day-of-year (+ day (* 31 (1- month)))))
235     (when (> month 2)
236       (setq day-of-year (- day-of-year (/ (+ 23 (* 4 month)) 10)))
237       (when (date-leap-year-p year)
238         (setq day-of-year (1+ day-of-year))))
239     day-of-year))
240
241 ;;;###autoload
242 (defun time-to-days (time)
243   "The number of days between the Gregorian date 0001-12-31bce and TIME.
244 TIME should be a time value.
245 The Gregorian date Sunday, December 31, 1bce is imaginary."
246   (let* ((tim (decode-time time))
247          (month (nth 4 tim))
248          (day (nth 3 tim))
249          (year (nth 5 tim)))
250     (+ (time-to-day-in-year time)       ;       Days this year
251        (* 365 (1- year))                ;       + Days in prior years
252        (/ (1- year) 4)                  ;       + Julian leap years
253        (- (/ (1- year) 100))            ;       - century years
254        (/ (1- year) 400))))             ;       + Gregorian leap years
255
256 (defun time-to-number-of-days (time)
257   "Return the number of days represented by TIME.
258 Returns a floating point number."
259   (/ (funcall (eval-when-compile
260                 (if (or (featurep 'emacs)
261                         (and (fboundp 'float-time)
262                              (subrp (symbol-function 'float-time))))
263                     'float-time
264                   'time-to-seconds)) time) (* 60 60 24)))
265
266 ;;;###autoload
267 (defun safe-date-to-time (date)
268   "Parse a string DATE that represents a date-time and return a time value.
269 If DATE is malformed, return a time value of zeros."
270   (condition-case ()
271       (date-to-time date)
272     (error '(0 0))))
273
274 \f
275 ;;;###autoload
276 (defun format-seconds (string seconds)
277   "Use format control STRING to format the number SECONDS.
278 The valid format specifiers are:
279 %y is the number of (365-day) years.
280 %d is the number of days.
281 %h is the number of hours.
282 %m is the number of minutes.
283 %s is the number of seconds.
284 %z is a non-printing control flag (see below).
285 %% is a literal \"%\".
286
287 Upper-case specifiers are followed by the unit-name (e.g. \"years\").
288 Lower-case specifiers return only the unit.
289
290 \"%\" may be followed by a number specifying a width, with an
291 optional leading \".\" for zero-padding.  For example, \"%.3Y\" will
292 return something of the form \"001 year\".
293
294 The \"%z\" specifier does not print anything.  When it is used, specifiers
295 must be given in order of decreasing size.  To the left of \"%z\", nothing
296 is output until the first non-zero unit is encountered.
297
298 This function does not work for SECONDS greater than `most-positive-fixnum'."
299   (let ((start 0)
300         (units '(("y" "year"   31536000)
301                  ("d" "day"       86400)
302                  ("h" "hour"       3600)
303                  ("m" "minute"       60)
304                  ("s" "second"        1)
305                  ("z")))
306         (case-fold-search t)
307         spec match usedunits zeroflag larger prev name unit num zeropos)
308     (while (string-match "%\\.?[0-9]*\\(.\\)" string start)
309       (setq start (match-end 0)
310             spec (match-string 1 string))
311       (unless (string-equal spec "%")
312         ;; `assoc-string' is not available in XEmacs.  So when compiling
313         ;; Gnus (`time-date.el' is part of Gnus) with XEmacs, we get
314         ;; a warning here.  But `format-seconds' is not used anywhere in
315         ;; Gnus so it's not a real problem. --rsteib
316         (or (setq match (assoc-string spec units t))
317             (error "Bad format specifier: `%s'" spec))
318         (if (assoc-string spec usedunits t)
319             (error "Multiple instances of specifier: `%s'" spec))
320         (if (string-equal (car match) "z")
321             (setq zeroflag t)
322           (unless larger
323             (setq unit (nth 2 match)
324                   larger (and prev (> unit prev))
325                   prev unit)))
326         (push match usedunits)))
327     (and zeroflag larger
328          (error "Units are not in decreasing order of size"))
329     (dolist (u units)
330       (setq spec (car u)
331             name (cadr u)
332             unit (nth 2 u))
333       (when (string-match (format "%%\\(\\.?[0-9]+\\)?\\(%s\\)" spec) string)
334         (if (string-equal spec "z")     ; must be last in units
335             (setq string
336                   (replace-regexp-in-string
337                    "%z" ""
338                    (substring string (min (or zeropos (match-end 0))
339                                           (match-beginning 0)))))
340           ;; Cf article-make-date-line in gnus-art.
341           (setq num (floor seconds unit)
342                 seconds (- seconds (* num unit)))
343           ;; Start position of the first non-zero unit.
344           (or zeropos
345               (setq zeropos (unless (zerop num) (match-beginning 0))))
346           (setq string
347                 (replace-match
348                  (format (concat "%" (match-string 1 string) "d%s") num
349                          (if (string-equal (match-string 2 string) spec)
350                              ""       ; lower-case, no unit-name
351                            (format " %s%s" name
352                                    (if (= num 1) "" "s"))))
353                  t t string))))))
354   (replace-regexp-in-string "%%" "%" string))
355
356
357 (provide 'time-date)
358
359 ;;; time-date.el ends here