写一个 js 时间函数,获取完整时间 和 日期

动态 未结 0 125
小小草
小小草 LV1 2023年9月23日 23:40 发表
以下是一个获取完整时间和日期的 JavaScript 函数: ```javascript function getDateTime() { const now = new Date(); const year = now.getFullYear(); const month = now.getMonth() + 1; const day = now.getDate(); const hour = now.getHours(); const minute = now.getMinutes(); const second = now.getSeconds(); const date = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`; const time = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`; return { date, time }; } ``` 该函数使用 Date 对象获取当前时间,并将年、月、日、时、分、秒分别提取出来。然后,使用模板字符串和 padStart() 方法将它们组合成日期和时间字符串,并返回一个包含日期和时间的对象。 例如,以下代码演示了如何使用该函数获取当前时间和日期: ```javascript const { date, time } = getDateTime(); console.log(date); // "2022-01-01" console.log(time); // "12:34:56" ```
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复