Merge from emacs--devo--0
[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  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 (defun date-to-time (date)
98   "Parse a string DATE that represents a date-time and return a time value."
99   (condition-case ()
100       (apply 'encode-time
101              (parse-time-string
102               ;; `parse-time-string' isn't sufficiently general or
103               ;; robust.  It fails to grok some of the formats that
104               ;; timezone does (e.g. dodgy post-2000 stuff from some
105               ;; Elms) and either fails or returns bogus values.  Lars
106               ;; reverted this change, but that loses non-trivially
107               ;; often for me.  -- fx
108               (timezone-make-date-arpa-standard date)))
109     (error (error "Invalid date: %s" date))))
110
111 ;;;###autoload
112 (defun time-to-seconds (time)
113   "Convert time value TIME to a floating point number.
114 You can use `float-time' instead."
115   (with-decoded-time-value ((high low micro time))
116     (+ (* 1.0 high 65536)
117        low
118        (/ micro 1000000.0))))
119
120 ;;;###autoload
121 (defun seconds-to-time (seconds)
122   "Convert SECONDS (a floating point number) to a time value."
123   (list (floor seconds 65536)
124         (floor (mod seconds 65536))
125         (floor (* (- seconds (ffloor seconds)) 1000000))))
126
127 ;;;###autoload
128 (defun time-less-p (t1 t2)
129   "Say whether time value T1 is less than time value T2."
130   (with-decoded-time-value ((high1 low1 micro1 t1)
131                             (high2 low2 micro2 t2))
132     (or (< high1 high2)
133         (and (= high1 high2)
134              (or (< low1 low2)
135                  (and (= low1 low2)
136                       (< micro1 micro2)))))))
137
138 ;;;###autoload
139 (defun days-to-time (days)
140   "Convert DAYS into a time value."
141   (let* ((seconds (* 1.0 days 60 60 24))
142          (high (condition-case nil (floor (/ seconds 65536))
143                  (range-error most-positive-fixnum))))
144     (list high (condition-case nil (floor (- seconds (* 1.0 high 65536)))
145                  (range-error 65535)))))
146
147 ;;;###autoload
148 (defun time-since (time)
149   "Return the time elapsed since TIME.
150 TIME should be either a time value or a date-time string."
151   (when (stringp time)
152     ;; Convert date strings to internal time.
153     (setq time (date-to-time time)))
154   (time-subtract (current-time) time))
155
156 ;;;###autoload
157 (defalias 'subtract-time 'time-subtract)
158
159 ;;;###autoload
160 (defun time-subtract (t1 t2)
161   "Subtract two time values, T1 minus T2.
162 Return the difference in the format of a time value."
163   (with-decoded-time-value ((high low micro type t1)
164                             (high2 low2 micro2 type2 t2))
165     (setq high (- high high2)
166           low (- low low2)
167           micro (- micro micro2)
168           type (max type type2))
169     (when (< micro 0)
170       (setq low (1- low)
171             micro (+ micro 1000000)))
172     (when (< low 0)
173       (setq high (1- high)
174             low (+ low 65536)))
175     (encode-time-value high low micro type)))
176
177 ;;;###autoload
178 (defun time-add (t1 t2)
179   "Add two time values T1 and T2.  One should represent a time difference."
180   (with-decoded-time-value ((high low micro type t1)
181                             (high2 low2 micro2 type2 t2))
182     (setq high (+ high high2)
183           low (+ low low2)
184           micro (+ micro micro2)
185           type (max type type2))
186     (when (>= micro 1000000)
187       (setq low (1+ low)
188             micro (- micro 1000000)))
189     (when (>= low 65536)
190       (setq high (1+ high)
191             low (- low 65536)))
192     (encode-time-value high low micro type)))
193
194 ;;;###autoload
195 (defun date-to-day (date)
196   "Return the number of days between year 1 and DATE.
197 DATE should be a date-time string."
198   (time-to-days (date-to-time date)))
199
200 ;;;###autoload
201 (defun days-between (date1 date2)
202   "Return the number of days between DATE1 and DATE2.
203 DATE1 and DATE2 should be date-time strings."
204   (- (date-to-day date1) (date-to-day date2)))
205
206 ;;;###autoload
207 (defun date-leap-year-p (year)
208   "Return t if YEAR is a leap year."
209   (or (and (zerop (% year 4))
210            (not (zerop (% year 100))))
211       (zerop (% year 400))))
212
213 ;;;###autoload
214 (defun time-to-day-in-year (time)
215   "Return the day number within the year corresponding to TIME."
216   (let* ((tim (decode-time time))
217          (month (nth 4 tim))
218          (day (nth 3 tim))
219          (year (nth 5 tim))
220          (day-of-year (+ day (* 31 (1- month)))))
221     (when (> month 2)
222       (setq day-of-year (- day-of-year (/ (+ 23 (* 4 month)) 10)))
223       (when (date-leap-year-p year)
224         (setq day-of-year (1+ day-of-year))))
225     day-of-year))
226
227 ;;;###autoload
228 (defun time-to-days (time)
229   "The number of days between the Gregorian date 0001-12-31bce and TIME.
230 TIME should be a time value.
231 The Gregorian date Sunday, December 31, 1bce is imaginary."
232   (let* ((tim (decode-time time))
233          (month (nth 4 tim))
234          (day (nth 3 tim))
235          (year (nth 5 tim)))
236     (+ (time-to-day-in-year time)       ;       Days this year
237        (* 365 (1- year))                ;       + Days in prior years
238        (/ (1- year) 4)                  ;       + Julian leap years
239        (- (/ (1- year) 100))            ;       - century years
240        (/ (1- year) 400))))             ;       + Gregorian leap years
241
242 (defun time-to-number-of-days (time)
243   "Return the number of days represented by TIME.
244 The number of days will be returned as a floating point number."
245   (/ (time-to-seconds time) (* 60 60 24)))
246
247 ;;;###autoload
248 (defun safe-date-to-time (date)
249   "Parse a string DATE that represents a date-time and return a time value.
250 If DATE is malformed, return a time value of zeros."
251   (condition-case ()
252       (date-to-time date)
253     (error '(0 0))))
254
255 \f
256 ;;;###autoload
257 (defun format-seconds (string seconds)
258   "Use format control STRING to format the number SECONDS.
259 The valid format specifiers are:
260 %y is the number of (365-day) years.
261 %d is the number of days.
262 %h is the number of hours.
263 %m is the number of minutes.
264 %s is the number of seconds.
265 %z is a non-printing control flag (see below).
266 %% is a literal \"%\".
267
268 Upper-case specifiers are followed by the unit-name (e.g. \"years\").
269 Lower-case specifiers return only the unit.
270
271 \"%\" may be followed by a number specifying a width, with an
272 optional leading \".\" for zero-padding.  For example, \"%.3Y\" will
273 return something of the form \"001 year\".
274
275 The \"%z\" specifier does not print anything.  When it is used, specifiers
276 must be given in order of decreasing size.  To the left of \"%z\", nothing
277 is output until the first non-zero unit is encountered.
278
279 This function does not work for SECONDS greater than `most-positive-fixnum'."
280   (let ((start 0)
281         (units '(("y" "year"   31536000)
282                  ("d" "day"       86400)
283                  ("h" "hour"       3600)
284                  ("m" "minute"       60)
285                  ("s" "second"        1)
286                  ("z")))
287         (case-fold-search t)
288         spec match usedunits zeroflag larger prev name unit num zeropos)
289     (while (string-match "%\\.?[0-9]*\\(.\\)" string start)
290       (setq start (match-end 0)
291             spec (match-string 1 string))
292       (unless (string-equal spec "%")
293         (or (setq match (assoc-string spec units t))
294             (error "Bad format specifier: `%s'" spec))
295         (if (assoc-string spec usedunits t)
296             (error "Multiple instances of specifier: `%s'" spec))
297         (if (string-equal (car match) "z")
298             (setq zeroflag t)
299           (unless larger
300             (setq unit (nth 2 match)
301                   larger (and prev (> unit prev))
302                   prev unit)))
303         (push match usedunits)))
304     (and zeroflag larger
305          (error "Units are not in decreasing order of size"))
306     (dolist (u units)
307       (setq spec (car u)
308             name (cadr u)
309             unit (nth 2 u))
310       (when (string-match (format "%%\\(\\.?[0-9]+\\)?\\(%s\\)" spec) string)
311         (if (string-equal spec "z")     ; must be last in units
312             (setq string
313                   (replace-regexp-in-string
314                    "%z" ""
315                    (substring string (min (or zeropos (match-end 0))
316                                           (match-beginning 0)))))
317           ;; Cf article-make-date-line in gnus-art.
318           (setq num (floor seconds unit)
319                 seconds (- seconds (* num unit)))
320           ;; Start position of the first non-zero unit.
321           (or zeropos
322               (setq zeropos (unless (zerop num) (match-beginning 0))))
323           (setq string
324                 (replace-match
325                  (format (concat "%" (match-string 1 string) "d%s") num
326                          (if (string-equal (match-string 2 string) spec)
327                              ""       ; lower-case, no unit-name
328                            (format " %s%s" name
329                                    (if (= num 1) "" "s"))))
330                  t t string))))))
331   (replace-regexp-in-string "%%" "%" string))
332
333
334 (provide 'time-date)
335
336 ;; arch-tag: addcf07b-b20a-465b-af72-550b8ac5190f
337 ;;; time-date.el ends here