JavaScript 如何获取一年中的第一天
给定一个日期/年份,任务是使用JavaScript获取该年份的第一天。
方法1
- 使用 getFullYear()方法 从给定的日期中获取年份。
- 使用new Date()函数使用年份、月份和日期创建新的日期对象。
示例: 此示例使用getFullYear()方法获得当前日期的完整年份,然后获得该年份的第一天。
let date = new Date();
console.log("Today = " + date);
// Use Date(year, month, day) function
console.log(new Date(date.getFullYear(), 0, 1));
输出
Today = Mon Jun 12 2023 02:10:43 GMT+0000 (Coordinated Universal Time)
2023-01-01T00:00:00.000Z
方法2
- 初始化变量year为2012。
- 使用 Date() 函数,使用year、month和day创建新的日期对象。
示例: 该示例使用2023年,然后获取该年的第一天。
let year = 2023;
console.log("Today's year = " + year);
// Use Date(year, month, day) function
// to get the first day of year
console.log(new Date(year, 0, 1));
输出
Today's year = 2023
2023-01-01T00:00:00.000Z