在 JavaScript 中获取当前日期时间有三种方法:使用 Date 对象,提供日期和时间属性,如 date.getDate()、date.getMonth() 等。使用 Date.now() 方法,返回自纪元以来的毫秒数。使用 ISO 标准格式字符串,包含年份、月份、日期、时、分、秒和毫秒时区偏移等信息。

在 JavaScript 中,获取当前日期时间有以下几种方法:
Date 对象表示一个日期和时间。可以通过以下方式创建一个新的 Date 对象:
<code class="js">const date = new Date();</code>
该对象包含当前日期和时间的信息,可以通过以下属性访问:
date.getDate(): 返回当前日期的日期(1-31)date.getMonth(): 返回当前日期的月份(0-11)date.getFullYear(): 返回当前日期的年份date.getHours(): 返回当前时间的时date.getMinutes(): 返回当前时间的分date.getSeconds(): 返回当前时间的秒date.getMilliseconds(): 返回当前时间的毫秒Date.now() 方法返回自纪元以来经过的毫秒数。可以通过以下方式使用它:
<code class="js">const msSinceEpoch = Date.now();</code>
JavaScript 中的 Date 对象可以转换为 ISO 8601 标准格式的字符串。该字符串包含以下信息:
可以使用以下语法获取 ISO 格式字符串:
<code class="js">const isoString = date.toISOString();</code>
获取当前日期和时间的示例代码:
<code class="js">const date = new Date();
const fullDate = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`;
const fullTime = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
console.log(`Current date: ${fullDate}`);
console.log(`Current time: ${fullTime}`);</code>输出:
<code>Current date: 31/12/2023 Current time: 12:00:00</code>
以上就是js中如何获取当前日期时间的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号