<h1id="title-non-xs"><ahref="index.html">The Common Lisp Cookbook</a>– Dates and Times</h1>
<!-- Announcement we can keep for 1 month or more. I remove it and re-add it from time to time. -->
<pclass="announce">
📹 <ahref="https://www.udemy.com/course/common-lisp-programming/?couponCode=6926D599AA-LISP4ALL">NEW! Learn Lisp in videos and support our contributors with this 40% discount.</a>
</p>
<pclass="announce-neutral">
📕 <ahref="index.html#download-in-epub">Get the EPUB and PDF</a>
</p>
<divid="content"
<p>Common Lisp provides two different ways of looking at time: universal time,
meaning time in the “real world”, and run time, meaning time as seen by your
computer’s CPU. We will deal with both of them separately.</p>
<p><aname="univ"></a></p>
<h2id="built-in-time-functions">Built-in time functions</h2>
<h3id="universal-time">Universal Time</h3>
<p>Universal time is represented as the number of seconds that have elapsed since
00:00 of January 1, 1900 in the GMT time zone. The function
<p><strong>NB</strong>: in the next section we’ll use the <code>local-time</code> library to get more user-friendy functions, such as <code>(local-time:universal-to-timestamp (get-universal-time))</code> which returns <code>@2021-06-25T09:16:29.000000+02:00</code>.</p>
<p>This call to <code>decode-universal-time</code> returns nine values: <code>seconds, minutes, hours, day, month, year, day of
the week, daylight savings time flag and time zone</code>. Note that the day of the
week is represented as an integer in the range 0..6 with 0 being Monday and 6
being Sunday. Also, the <strong>time zone</strong> is represented as the number of hours you need
to add to the current time in order to get GMT time.</p>
<p>So in this example the
decoded time would be <code>19:22:06 of Friday, January 25, 2002</code>, in the EST time
zone, with no daylight savings in effect. This, of course, relies on the
computer’s own clock, so make sure that it is set correctly (including the time
zone you are in and the DST flag). As a shortcut, you can use
<p>Note that the result is automatically adjusted for daylight savings time if the time zone is not supplied. If it is supplied, than Lisp assumes that the specified time zone already accounts for daylight savings time, and no adjustment is performed.</p>
<p>Since universal times are simply numbers, they are easier and safer to manipulate than calendar times. Dates and times should always be stored as universal times if possible, and only converted to string representations for output purposes. For example, it is straightforward to know which of two dates came before the other, by simply comparing the two corresponding universal times with <code><</code>.</p>
<h3id="internal-time">Internal Time</h3>
<p>Internal time is the time as measured by your Lisp environment, using your computer’s clock. It differs from universal time in three important respects. First, internal time is not measured starting from a specified point in time: it could be measured from the instant you started your Lisp, from the instant you booted your machine, or from any other arbitrary time point in the past. As we will see shortly, the absolute value of an internal time is almost always meaningless; only differences between internal times are useful. The second difference is that internal time is not measured in seconds, but in a (usually smaller) unit whose value can be deduced from <ahref="http://www.lispworks.com/documentation/HyperSpec/Body/v_intern.htm"><code>internal-time-units-per-second</code></a>:</p>
<p>This means that in the Lisp environment used in this example, internal time is measured in milliseconds.</p>
<p>Finally, what is being measured by the “internal time” clock? There are actually two different internal time clocks in your Lisp:</p>
<ul>
<li>one of them measures the passage of “real” time (the same time that universal time measures, but in different units), and</li>
<li>the other one measures the passage of CPU time, that is, the time your CPU spends doing actual computation for the current Lisp process.</li>
</ul>
<p>On most modern computers these two times will be different, since your CPU will never be entirely dedicated to your program (even on single-user machines, the CPU has to devote part of its time to processing interrupts, performing I/O, etc). The two functions used to retrieve internal times are called <ahref="http://www.lispworks.com/documentation/HyperSpec/Body/f_get_in.htm"><code>get-internal-real-time</code></a> and <ahref="http://www.lispworks.com/documentation/HyperSpec/Body/f_get__1.htm"><code>get-internal-run-time</code></a> respectively. Using them, we can solve the above problem about measuring a function’s run time, which is what the <code>time</code> built-in macro does.</p>
<p>The <ahref="https://common-lisp.net/project/local-time/">local-time</a> library (<ahref="https://github.com/dlowe-net/local-time/">GitHub</a>) is a very handy extension to
the somewhat limited functionalities as defined by the standard.</p>
<p>In particular, it can</p>
<ul>
<li>print timestamps in various standard or custom formats (e.g. RFC1123 or RFC3339)</li>
<li>parse timestrings,</li>
<li>perform time arithmetic,</li>
<li>convert Unix times, timestamps, and universal times to and from.</li>
</ul>
<p>We present below what we find the most useful functions. See its <ahref="https://common-lisp.net/project/local-time/manual.html">manual</a> for the full details.</p>
<pre><code>**encode-timestamp** nsec sec minute hour day month year &key timezone offset into
The offset is the number of seconds offset from UTC of the locale. If offset is not specified, the offset will be guessed from the timezone. If a timestamp is passed as the into argument, its value will be set and that timestamp will be returned. Otherwise, a new timestamp is created.
</code></pre>
<p>Create a timestamp from a universal time with <code>universal-to-timestamp</code>:</p>
<p>But see the section on parsing timestrings for more.</p>
<h3id="get-todays-date-now-today">Get today’s date (now, today)</h3>
<p>Use <code>now</code> or <code>today</code>:</p>
<pre><codeclass="language-lisp">(local-time:now)
@2019-11-13T20:02:13.529541+01:00
(local-time:today)
@2019-11-13T01:00:00.000000+01:00
</code></pre>
<p>“today” is the midnight of the current day in the UTC zone.</p>
<p>To compute “yesterday” and “tomorrow”, see below.</p>
<h3id="add-or-substract-times-timestamp-timestamp-">Add or substract times (timestamp+, timestamp-)</h3>
<p>Use <code>timestamp+</code> and <code>timestamp-</code>. Each takes 3 arguments: a date, a number and a unit (and optionally a timezone and an offset):</p>
<pre><codeclass="language-lisp">(local-time:now)
@2021-06-25T07:19:39.836973+02:00
(local-time:timestamp+ (local-time:now) 1 :day)
@2021-06-26T07:16:58.086226+02:00
(local-time:timestamp- (local-time:now) 1 :day)
@2021-06-24T07:17:02.861763+02:00
</code></pre>
<p>The available units are <code>:sec :minute :hour :day :year</code>.</p>
<p>This operation is also possible with <code>adjust-timestamp</code>, which can do a bit more as we’ll see right in the next section (it can do many operations at once).</p>
"Returns a timestamp representing the day before today."
(timestamp- (today) 1 :day))
(defun tomorrow ()
"Returns a timestamp representing the day after today."
(timestamp+ (today) 1 :day))
</code></pre>
<h3id="modify-timestamps-with-any-offset-adjust-timestamp">Modify timestamps with any offset (adjust-timestamp)</h3>
<p><code>adjust-timestamp</code>’s first argument is the timestamp we operate on, and then it accepts a full <code>&body changes</code> where a “change” is in the form <code>(offset :part value)</code>:</p>
<p>If you have a list of timestamps, use <code>(apply #'timestamp-minimum <your list of timestamps>)</code>.</p>
<h3id="maximize-or-minimize-a-timestamp-according-to-a-time-unit-timestamp-maximize-part-timestamp-minimize-part">Maximize or minimize a timestamp according to a time unit (timestamp-maximize-part, timestamp-minimize-part)</h3>
<p>We can answer quite a number of questions with this handy function.</p>
<p>Here’s an example: please give me the last day of this month:</p>
<h3id="querying-timestamp-objects-get-the-day-the-day-of-week-the-days-in-month">Querying timestamp objects (get the day, the day of week, the days in month…)</h3>
<p>You can of course bind each time unit (<code>:sec :minute :day</code>) to its variable, in any order.</p>
<p>See also <code>(days-in-month <month><year>)</code>.</p>
<h3id="formatting-time-strings-format-format-timestring-iso-8601-format">Formatting time strings (format, format-timestring, +iso-8601-format+)</h3>
<p>local-time’s date representation starts with <code>@</code>. We can <code>format</code> them as usual, with the aesthetic directive for instance, to get a usual date representation.</p>
<p>Here <code>nil</code> returns a new string. <code>t</code> would print to <code>*standard-output*</code>.</p>
<p>But <code>format-timestring</code> also accepts a <code>:format</code> argument. We can use predefined date formats as well as give our own in s-expression friendly way (see next section).</p>
<p>Its default value is
<code>+iso-8601-format+</code>, with the output shown above. The <code>+rfc3339-format+</code> format defaults to it.</p>
<p>The list of symbols is available in the documentation: <ahref="https://common-lisp.net/project/local-time/manual.html#Parsing-and-Formatting">https://common-lisp.net/project/local-time/manual.html#Parsing-and-Formatting</a></p>
<p>There are <code>:year :month :day :weekday :hour :min :sec :msec</code>, long and
short notations (“Monday”, “Mo.”), gmt offset, timezone markers and
more.</p>
<p>The <code>+rfc-1123-format+</code> itself is defined like this:</p>
<p>Parses a timestring and returns the corresponding timestamp. Parsing begins at start and stops at the end position. If there are invalid characters within timestring and fail-on-error is T, then an invalid-timestring error is signaled, otherwise NIL is returned.</p>
<p>If there is no timezone specified in timestring then offset is used as the default timezone offset (in seconds).</p>