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