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