Submitted by gwagner on
While date/time information items have to be formated as strings in a
human-readable form on web pages, preferably in localized form based on the
settings of the user's browser, it's not a good idea to store date/time
values in this form. Rather we use instances of the pre-defined JavaScript
class Date
for representing and storing date/time values. In
this form, the pre-defined functions toISOString()
and
toLocaleDateString()
can be used for turning Date
values into ISO standard date/time strings (of the form "2015-01-27") or to
localized date/time strings (like "27.1.2015"). Notice that, for simplicity,
we have omitted the time part of the date/time strings.
In summary, a date/time value is expressed in three different forms:
-
Internally, for storage and computations, as a
Date
value. -
Internally, for annotating localized date/time strings, or externally, for displaying a date/time value in a standard form, as an ISO standard date/time string, e.g., with the help of
toISOString()
. -
Externally, for displaying a date/time value in a localized form, as a localized date/time string, e.g., with the help of
toLocaleDateString()
.
When a date/time value is to be included in a web page, we can use the
<time>
element that allows to display a human-readable
representation (typically a localized date/time string) that is annotated
with a standard (machine-readable) form of the date/time value.
We illustrate the use of the <time>
element with the
following example of a web page that includes two <time>
elements: one for displaying a fixed date, and another (initially empty)
element for displaying the date of today, which is computed with the help of
a JavaScript function. In both cases we use the datetime
attribute for annotating the displayed human-readable date with the
corresponding machine-readable representation.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8" /> <title>Using the HTML5 Time Element</title> <script> function assignDate() { var dateEl = document.getElementById("today"); var today = new Date(); dateEl.textContent = today.toLocaleDateString(); dateEl.setAttribute("datetime", today.toISOString()); } window.addEventListener("load", assignDate); </script> </head> <body> <h1>HTML5 Time Element</h1> <p>HTML 2.0 was published on <time datetime="1995-11-24">24.11.1995</time>.</p> <p>Today is <time id="today" datetime=""></time>.</p> </body> </html>
After this web page is loaded, the JavaScript function
assignDate()
is executed. It computes today's date as a
Date
value and assigns the ISO standard representation to
the <time>
element's datetime
attribute
and the localized representation as the text content of the
<time>
element:.