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