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