js 获取年月日

在前端开发中,经常会遇到需要获取当前日期的情况。JavaScript 提供了一些方便的方法来获取当前的年、月和日,让我们来详细了解一下。
获取当前日期
JavaScript 提供了 Date 对象来处理日期和时间,可以通过 Date 对象来获取当前的日期。
// 创建一个 Date 对象
let currentDate = new Date();
// 获取当前年份
let currentYear = currentDate.getFullYear();
// 获取当前月份(注意月份是从 0 开始计数的)
let currentMonth = currentDate.getMonth() + 1;
// 获取当前日期
let currentDay = currentDate.getDate();
console.log(`当前日期是:{currentYear}年{currentMonth}月${currentDay}日`);
运行上面的代码,打印出当前日期,例如:
当前日期是:2021年3月12日
获取特定日期的年月日
除了获取当前日期外,有时也需要获取特定日期的年、月和日。可以通过指定日期的方式来创建 Date 对象,并调用相应的方法来获取年、月和日。
// 指定一个特定日期来创建 Date 对象
let specificDate = new Date('2021-12-25');
let specificYear = specificDate.getFullYear();
let specificMonth = specificDate.getMonth() + 1;
let specificDay = specificDate.getDate();
console.log(`指定日期的年月日为:{specificYear}年{specificMonth}月${specificDay}日`);
运行上面的代码,输出指定日期的年月日,如:
指定日期的年月日为:2021年12月25日
获取今天的年月日
有时候可能只需要获取今天的日期,而不需要包含时间。可以通过一些方法来获取只有年月日部分的日期。
// 获取今天的日期
let today = new Date();
// 获取年份
let year = today.getFullYear();
// 获取月份
let month = today.getMonth() + 1;
// 获取日期
let day = today.getDate();
console.log(`今天的日期是:{year}年{month}月${day}日`);
运行上述代码,将得到今天的日期信息,例如:
今天的日期是:2021年3月12日
总结
通过以上介绍,我们学习了如何使用 JavaScript 获取当前日期、特定日期的年、月、日信息,以及如何获取今天的年月日。这在前端开发中经常会用到,能够帮助我们更好地处理日期相关的逻辑。
极客笔记