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