在 JavaScript 中获取当前年月日方法如下:获取年、月、日:使用 Date 对象的 getFullYear()、getMonth() 和 getDate() 方法。格式化输出:使用 String.prototype.padStart() 和 String.prototype.padEnd() 方法,补齐月份和日期为两位数,并以连字符连接。获取时间:使用 Date 对象的 getHours()、getMinutes() 和 getSeconds() 方法。格式化输出时间:同上,补齐小时、分

如何在 JavaScript 中获取当前年月日
获取年、月、日
获取当前年月日,可以使用 JavaScript 的 Date 对象:
<code class="javascript">const date = new Date(); const year = date.getFullYear(); const month = date.getMonth() + 1; // 注意:JavaScript 中月份是从 0 开始的 const day = date.getDate();</code>
结果:
<code>year: 2022 month: 7 day: 19</code>
要将年月日格式化为一个字符串,可以使用 String.prototype.padStart() 和 String.prototype.padEnd() 方法:
<code class="javascript">const paddedMonth = month.toString().padStart(2, '0');
const paddedDay = day.toString().padStart(2, '0');
const formattedDate = `${year}-${paddedMonth}-${paddedDay}`;</code>结果:
<code>formattedDate: "2022-07-19"</code>
获取时间
除了年月日之外,还可以使用 Date 对象获取当前时间:
<code class="javascript">const hours = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds();</code>
结果:
<code>hours: 11 minutes: 30 seconds: 25</code>
格式化输出时间
可以使用 String.prototype.padStart() 和 String.prototype.padEnd() 方法来格式化时间:
<code class="javascript">const paddedHours = hours.toString().padStart(2, '0');
const paddedMinutes = minutes.toString().padStart(2, '0');
const paddedSeconds = seconds.toString().padStart(2, '0');
const formattedTime = `${paddedHours}:${paddedMinutes}:${paddedSeconds}`;</code>结果:
<code>formattedDate: "11:30:25"</code>
以上就是js怎么获取当前年月日的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号