46e38ae46a80104ff1ccaf5cd9281f612e3ea276
[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 three formats.  The oldest format is a cons
27 ;; cell of the form (HIGH . LOW).  This format is obsolete, but still
28 ;; supported.  The two other formats are the lists (HIGH LOW) and
29 ;; (HIGH LOW MICRO).  The first two formats specify HIGH * 2^16 + LOW
30 ;; seconds; the third format specifies HIGH * 2^16 + LOW + MICRO /
31 ;; 1000000 seconds.  We should have 0 <= MICRO < 1000000 and 0 <= LOW
32 ;; < 2^16.  If the time value represents a point in time, then HIGH is
33 ;; nonnegative.  If the time value is a time difference, then HIGH can
34 ;; be negative as well.  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 [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
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), and type 2 is the list (HIGH LOW MICRO)."
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              (type (unless (eq (length elt) 1)
63                      (pop elt)))
64              (time-value (car elt))
65              (gensym (make-symbol "time")))
66         `(let* ,(append `((,gensym ,time-value)
67                           (,high (pop ,gensym))
68                           ,low ,micro)
69                         (when type `(,type)))
70            (if (consp ,gensym)
71                (progn
72                  (setq ,low (pop ,gensym))
73                  (if ,gensym
74                      ,(append `(setq ,micro (car ,gensym))
75                               (when type `(,type 2)))
76                    ,(append `(setq ,micro 0)
77                             (when type `(,type 1)))))
78              ,(append `(setq ,low ,gensym ,micro 0)
79                       (when type `(,type 0))))
80            (with-decoded-time-value ,varlist ,@body)))
81     `(progn ,@body)))
82
83 (defun encode-time-value (high low micro type)
84   "Encode HIGH, LOW, and MICRO into a time value of type TYPE.
85 Type 0 is the cons cell (HIGH . LOW), type 1 is the list (HIGH LOW),
86 and type 2 is the list (HIGH LOW MICRO)."
87   (cond
88    ((eq type 0) (cons high low))
89    ((eq type 1) (list high low))
90    ((eq type 2) (list high low micro))))
91
92 (autoload 'parse-time-string "parse-time")
93 (autoload 'timezone-make-date-arpa-standard "timezone")
94
95 ;;;###autoload
96 ;; `parse-time-string' isn't sufficiently general or robust.  It fails
97 ;; to grok some of the formats that timezone does (e.g. dodgy
98 ;; post-2000 stuff from some Elms) and either fails or returns bogus
99 ;; values.  timezone-make-date-arpa-standard should help.
100 (defun date-to-time (date)
101   "Parse a string DATE that represents a date-time and return a time value.
102 If DATE lacks timezone information, GMT is assumed."
103   (condition-case ()
104       (apply 'encode-time (parse-time-string date))
105     (error (condition-case ()
106                (apply 'encode-time
107                       (parse-time-string
108                        (timezone-make-date-arpa-standard date)))
109              (error (error "Invalid date: %s" date))))))
110
111 ;; Bit of a mess.  Emacs has float-time since at least 21.1.
112 ;; This file is synced to Gnus, and XEmacs packages may have been written
113 ;; using time-to-seconds from the Gnus library.
114 ;;;###autoload(if (or (featurep 'emacs)
115 ;;;###autoload        (and (fboundp 'float-time)
116 ;;;###autoload             (subrp (symbol-function 'float-time))))
117 ;;;###autoload    (progn
118 ;;;###autoload      (defalias 'time-to-seconds 'float-time)
119 ;;;###autoload      (make-obsolete 'time-to-seconds 'float-time "21.1"))
120 ;;;###autoload  (autoload 'time-to-seconds "time-date"))
121
122 (eval-when-compile
123   (or (featurep 'emacs)
124       (and (fboundp 'float-time)
125            (subrp (symbol-function 'float-time)))
126       (defun time-to-seconds (time)
127         "Convert time value TIME to a floating point number."
128         (with-decoded-time-value ((high low micro time))
129           (+ (* 1.0 high 65536)
130              low
131              (/ micro 1000000.0))))))
132
133 ;;;###autoload
134 (defun seconds-to-time (seconds)
135   "Convert SECONDS (a floating point number) to a time value."
136   (list (floor seconds 65536)
137         (floor (mod seconds 65536))
138         (floor (* (- seconds (ffloor seconds)) 1000000))))
139
140 ;;;###autoload
141 (defun time-less-p (t1 t2)
142   "Return non-nil if time value T1 is earlier than time value T2."
143   (with-decoded-time-value ((high1 low1 micro1 t1)
144                             (high2 low2 micro2 t2))
145     (or (< high1 high2)
146         (and (= high1 high2)
147              (or (< low1 low2)
148                  (and (= low1 low2)
149                       (< micro1 micro2)))))))
150
151 ;;;###autoload
152 (defun days-to-time (days)
153   "Convert DAYS into a time value."
154   (let* ((seconds (* 1.0 days 60 60 24))
155          (high (condition-case nil (floor (/ seconds 65536))
156                  (range-error most-positive-fixnum))))
157     (list high (condition-case nil (floor (- seconds (* 1.0 high 65536)))
158                  (range-error 65535)))))
159
160 ;;;###autoload
161 (defun time-since (time)
162   "Return the time elapsed since TIME.
163 TIME should be either a time value or a date-time string."
164   (when (stringp time)
165     ;; Convert date strings to internal time.
166     (setq time (date-to-time time)))
167   (time-subtract (current-time) time))
168
169 ;;;###autoload
170 (defalias 'subtract-time 'time-subtract)
171
172 ;;;###autoload
173 (defun time-subtract (t1 t2)
174   "Subtract two time values, T1 minus T2.
175 Return the difference in the format of a time value."
176   (with-decoded-time-value ((high low micro type t1)
177                             (high2 low2 micro2 type2 t2))
178     (setq high (- high high2)
179           low (- low low2)
180           micro (- micro micro2)
181           type (max type type2))
182     (when (< micro 0)
183       (setq low (1- low)
184             micro (+ micro 1000000)))
185     (when (< low 0)
186       (setq high (1- high)
187             low (+ low 65536)))
188     (encode-time-value high low micro type)))
189
190 ;;;###autoload
191 (defun time-add (t1 t2)
192   "Add two time values T1 and T2.  One should represent a time difference."
193   (with-decoded-time-value ((high low micro type t1)
194                             (high2 low2 micro2 type2 t2))
195     (setq high (+ high high2)
196           low (+ low low2)
197           micro (+ micro micro2)
198           type (max type type2))
199     (when (>= micro 1000000)
200       (setq low (1+ low)
201             micro (- micro 1000000)))
202     (when (>= low 65536)
203       (setq high (1+ high)
204             low (- low 65536)))
205     (encode-time-value high low micro type)))
206
207 ;;;###autoload
208 (defun date-to-day (date)
209   "Return the number of days between year 1 and DATE.
210 DATE should be a date-time string."
211   (time-to-days (date-to-time date)))
212
213 ;;;###autoload
214 (defun days-between (date1 date2)
215   "Return the number of days between DATE1 and DATE2.
216 DATE1 and DATE2 should be date-time strings."
217   (- (date-to-day date1) (date-to-day date2)))
218
219 ;;;###autoload
220 (defun date-leap-year-p (year)
221   "Return t if YEAR is a leap year."
222   (or (and (zerop (% year 4))
223            (not (zerop (% year 100))))
224       (zerop (% year 400))))
225
226 ;;;###autoload
227 (defun time-to-day-in-year (time)
228   "Return the day number within the year corresponding to TIME."
229   (let* ((tim (decode-time time))
230          (month (nth 4 tim))
231          (day (nth 3 tim))
232          (year (nth 5 tim))
233          (day-of-year (+ day (* 31 (1- month)))))
234     (when (> month 2)
235       (setq day-of-year (- day-of-year (/ (+ 23 (* 4 month)) 10)))
236       (when (date-leap-year-p year)
237         (setq day-of-year (1+ day-of-year))))
238     day-of-year))
239
240 ;;;###autoload
241 (defun time-to-days (time)
242   "The number of days between the Gregorian date 0001-12-31bce and TIME.
243 TIME should be a time value.
244 The Gregorian date Sunday, December 31, 1bce is imaginary."
245   (let* ((tim (decode-time time))
246          (year (nth 5 tim)))
247     (+ (time-to-day-in-year time)       ;       Days this year
248        (* 365 (1- year))                ;       + Days in prior years
249        (/ (1- year) 4)                  ;       + Julian leap years
250        (- (/ (1- year) 100))            ;       - century years
251        (/ (1- year) 400))))             ;       + Gregorian leap years
252
253 (defun time-to-number-of-days (time)
254   "Return the number of days represented by TIME.
255 Returns a floating point number."
256   (/ (funcall (eval-when-compile
257                 (if (or (featurep 'emacs)
258                         (and (fboundp 'float-time)
259                              (subrp (symbol-function 'float-time))))
260                     'float-time
261                   'time-to-seconds)) time) (* 60 60 24)))
262
263 ;;;###autoload
264 (defun safe-date-to-time (date)
265   "Parse a string DATE that represents a date-time and return a time value.
266 If DATE is malformed, return a time value of zeros."
267   (condition-case ()
268       (date-to-time date)
269     (error '(0 0))))
270
271 \f
272 ;;;###autoload
273 (defun format-seconds (string seconds)
274   "Use format control STRING to format the number SECONDS.
275 The valid format specifiers are:
276 %y is the number of (365-day) years.
277 %d is the number of days.
278 %h is the number of hours.
279 %m is the number of minutes.
280 %s is the number of seconds.
281 %z is a non-printing control flag (see below).
282 %% is a literal \"%\".
283
284 Upper-case specifiers are followed by the unit-name (e.g. \"years\").
285 Lower-case specifiers return only the unit.
286
287 \"%\" may be followed by a number specifying a width, with an
288 optional leading \".\" for zero-padding.  For example, \"%.3Y\" will
289 return something of the form \"001 year\".
290
291 The \"%z\" specifier does not print anything.  When it is used, specifiers
292 must be given in order of decreasing size.  To the left of \"%z\", nothing
293 is output until the first non-zero unit is encountered.
294
295 This function does not work for SECONDS greater than `most-positive-fixnum'."
296   (let ((start 0)
297         (units '(("y" "year"   31536000)
298                  ("d" "day"       86400)
299                  ("h" "hour"       3600)
300                  ("m" "minute"       60)
301                  ("s" "second"        1)
302                  ("z")))
303         (case-fold-search t)
304         spec match usedunits zeroflag larger prev name unit num zeropos)
305     (while (string-match "%\\.?[0-9]*\\(.\\)" string start)
306       (setq start (match-end 0)
307             spec (match-string 1 string))
308       (unless (string-equal spec "%")
309         (or (setq match (assoc (downcase spec) units))
310             (error "Bad format specifier: `%s'" spec))
311         (if (assoc (downcase spec) usedunits)
312             (error "Multiple instances of specifier: `%s'" spec))
313         (if (string-equal (car match) "z")
314             (setq zeroflag t)
315           (unless larger
316             (setq unit (nth 2 match)
317                   larger (and prev (> unit prev))
318                   prev unit)))
319         (push match usedunits)))
320     (and zeroflag larger
321          (error "Units are not in decreasing order of size"))
322     (dolist (u units)
323       (setq spec (car u)
324             name (cadr u)
325             unit (nth 2 u))
326       (when (string-match (format "%%\\(\\.?[0-9]+\\)?\\(%s\\)" spec) string)
327         (if (string-equal spec "z")     ; must be last in units
328             (setq string
329                   (replace-regexp-in-string
330                    "%z" ""
331                    (substring string (min (or zeropos (match-end 0))
332                                           (match-beginning 0)))))
333           ;; Cf article-make-date-line in gnus-art.
334           (setq num (floor seconds unit)
335                 seconds (- seconds (* num unit)))
336           ;; Start position of the first non-zero unit.
337           (or zeropos
338               (setq zeropos (unless (zerop num) (match-beginning 0))))
339           (setq string
340                 (replace-match
341                  (format (concat "%" (match-string 1 string) "d%s") num
342                          (if (string-equal (match-string 2 string) spec)
343                              ""       ; lower-case, no unit-name
344                            (format " %s%s" name
345                                    (if (= num 1) "" "s"))))
346                  t t string))))))
347   (replace-regexp-in-string "%%" "%" string))
348
349
350 (provide 'time-date)
351
352 ;;; time-date.el ends here