在JS获取当前的时间,当前的时间戳转化为年月日时分秒
warning:
这篇文章距离上次修改已过449天,其中的内容可能已经有所变动。
在JavaScript中,获取当前时间可以使用 Date 对象,将 Date 对象转换为年月日时分秒可以使用 getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds() 方法。
以下是示例代码:
// 获取当前时间
const now = new Date();
// 获取年月日时分秒
const year = now.getFullYear();
const month = now.getMonth() + 1; // 月份是从0开始的
const day = now.getDate();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
// 输出格式化后的时间
console.log(`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
// 如果需要时间戳(单位:毫秒)
const timestamp = now.getTime();
console.log(timestamp);注意:getMonth() 方法返回的月份值是从0到11的整数,因此在使用时需要加1来得到常规的月份表示。
评论已关闭