JavaScript 中的 Date
对象用于处理日期和时间。
基础概念:
Date
对象提供了多种方法来获取和设置日期和时间的各个部分,如年、月、日、小时、分钟、秒等。new Date()
来创建一个表示当前日期和时间的 Date
对象,也可以传入特定的参数来创建指定日期和时间的对象。优势:
类型:
应用场景:
示例代码:
// 创建一个表示当前日期和时间的 Date 对象
let now = new Date();
console.log(now);
// 获取年份
let year = now.getFullYear();
console.log(year);
// 获取月份(0 - 11,需要加 1)
let month = now.getMonth() + 1;
console.log(month);
// 获取日期
let day = now.getDate();
console.log(day);
// 格式化日期为 "YYYY-MM-DD"
let formattedDate = `${year}-${month < 10? '0' + month : month}-${day < 10? '0' + day : day}`;
console.log(formattedDate);
常见问题及解决方法:
getTime()
方法获取时间戳进行计算,然后再转换回 Date
对象。领取专属 10元无门槛券
手把手带您无忧上云