HTML datetime 属性用于指示与元素关联的日期和时间。
它用于指定插入或删除文本的日期和时间。datetime 属性的值必须采用带有可选时间字符串的有效格式。如果无法将该值解析为具有可选时间字符串的日期,则该元素没有关联的时间戳。
语法
<tag datetime = "value"></tag>
其中 value 可以是任何日期和时间,格式如下:
Year-month-day or 2023-07-11 or 2023-07-11T15:17:00
适用于
下面列出的元素允许使用 HTML datetime 属性
元素 | 描述 |
---|---|
<del> | HTML <del> 标签用于标记网站上已删除的文本内容。 |
<ins> | HTML <ins> 标签表示已插入到 HTML 文档中的文本范围。 |
<time> | HTML <time> 标签用于定义特定的日期和时间。 |
HTML datetime 属性的示例
下面的示例将说明 HTML datetime 属性,我们应该在哪里以及如何使用此属性!
定义已删除元素的日期时间
在以下示例中,我们在 <del> 标记中使用 HTML 'datetime' 属性来指示与此元素关联的日期和时间。
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML 'datetime' attribute</title>
</head>
<body>
<!--HTML 'datetime' attribute-->
<p>Example of the HTML 'datetime' attribute</p>
<del datetime="2023-07-11T14:26:00">
Text within the 'del' tag has been deleted.
</del>
</body>
</html>
定义插入元素的日期时间
考虑到另一种情况,我们将使用 datetime 属性和 ins 标签。
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML 'datetime' attribute</title>
</head>
<body>
<!--HTML 'datetime' attribute-->
<p>Example of the HTML 'datetime' attribute</p>
<ins datetime="2023-07-11T14:42:04">
Text inserted within the 'ins' element.
</ins>
</body>
</html>
带有时间标签的 Datetime 属性
让我们看一下以下示例,我们将在其中使用 datetime 属性和 time 标签,并使用 javascript 打印当前时间。这用于机器的可读性。
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML 'datetime' attribute</title>
</head>
<body>
<!--HTML 'datetime' attribute-->
<p>Example of the HTML 'datetime' attribute</p>
<h3>HTML 'datetime' attribute with 'time' element</h3>
<p>The concert is on
<time datetime="2023-07-15T15:02:00">
15 July</time>
</p>
<p>Current time is:
<time datetime="2023-07-11T15:03:00" id='demo'></time>
</p>
<script>
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var res = document.getElementById('demo');
res.innerHTML = h + " : " + m + " : " + s;
</script>
</body>
</html>
支持的浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
是否支持 | 62.0 | 18.0 | 22.0 | 7.0 | 49.0 |