JS new Date()只保留年月
1. 概述
在JavaScript中,我们经常需要处理日期和时间。JavaScript提供了Date对象来处理日期和时间相关的操作。当我们使用new Date()
构造函数创建一个Date对象时,默认情况下会返回当前的完整日期和时间。
但是,在某些情况下,我们可能只对年份和月份感兴趣,而对具体的日期和时间则不敏感。本文将介绍如何使用JavaScript的Date对象,并通过一些示例演示如何只保留日期和时间中的年份和月份。
2. Date对象简介
Date对象是JavaScript中用于处理日期和时间的内置对象。我们可以使用new Date()
构造函数来创建一个新的Date对象。对于该构造函数的调用,可以传递以下参数:
- 无参数:返回当前时间的Date对象。
- 一个整数代表毫秒数:该整数表示自1970年1月1日 00:00:00 UTC(协调世界时)起经过的毫秒数。
- 一个代表日期字符串的字符串:该字符串表示特定日期和时间的字符串格式。
下面是几个示例:
// 返回当前时间的Date对象
const currentDate = new Date();
console.log(currentDate);
// 传入一个整数代表毫秒数,返回指定时间的Date对象
const specificDate = new Date(1616703421000);
console.log(specificDate);
// 传入一个代表日期字符串的字符串,返回指定日期的Date对象
const specifiedDate = new Date("2022-04-01T09:30:00");
console.log(specifiedDate);
运行以上代码,我们可以看到如下输出:
Sat Mar 26 2022 19:50:21 GMT+0800 (中国标准时间)
Fri Aug 12 2022 23:23:41 GMT+0800 (中国标准时间)
Fri Apr 01 2022 09:30:00 GMT+0800 (中国标准时间)
3. Date对象的方法
除了可以用于创建Date对象,Date对象还提供了一些方法来获取、设置和操作日期和时间。下面列举了一些常用的方法:
3.1 获取年份、月份和日期
我们可以使用Date对象的getFullYear()
、getMonth()
和getDate()
方法获取当前日期的年份、月份和日期。这些方法返回的都是本地对应的值。
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = currentDate.getMonth();
const date = currentDate.getDate();
console.log(year, month, date);
以上代码将返回当前日期的年份、月份和日期。
3.2 设置年份、月份和日期
我们可以使用Date对象的setFullYear()
、setMonth()
和setDate()
方法来设置日期的年份、月份和日期。这些方法可以传递一个整数作为参数来设置对应的值。
const currentDate = new Date();
currentDate.setFullYear(2023);
currentDate.setMonth(6);
currentDate.setDate(15);
console.log(currentDate);
以上代码将设置当前日期为2023年7月15日。
3.3 获取和设置日期的时间部分
除了年份、月份和日期,Date对象还包含时间部分,包括小时、分钟、秒和毫秒。我们可以使用getHours()
、getMinutes()
、getSeconds()
和getMilliseconds()
方法来获取当前日期的时间部分。
const currentDate = new Date();
const hours = currentDate.getHours();
const minutes = currentDate.getMinutes();
const seconds = currentDate.getSeconds();
const milliseconds = currentDate.getMilliseconds();
console.log(hours, minutes, seconds, milliseconds);
以上代码将返回当前日期的小时、分钟、秒和毫秒。
我们也可以使用setHours()
、setMinutes()
、setSeconds()
和setMilliseconds()
方法来设置日期的时间部分。
3.4 只保留年份和月份
根据题目要求,我们只关心年份和月份,并且忽略具体的日期和时间。我们可以使用setDate()
方法来设置日期为1,使得日期部分变为1号,然后再将时间部分设置为0。
const currentDate = new Date();
currentDate.setDate(1);
currentDate.setHours(0);
currentDate.setMinutes(0);
currentDate.setSeconds(0);
currentDate.setMilliseconds(0);
console.log(currentDate);
以上代码将只保留年份和月份,并将日期部分设置为1号,时间部分设置为0。
4. 示例
下面是一个完整的示例,演示如何使用JavaScript的Date对象只保留年份和月份:
function getYearAndMonth() {
const date = new Date();
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
const year = date.getFullYear();
const month = date.getMonth();
return { year, month };
}
const { year, month } = getYearAndMonth();
console.log(year, month);
以上代码将返回当前年份和月份,并忽略具体的日期和时间。
5. 结论
本文介绍了如何使用JavaScript的Date对象来处理日期和时间,并演示了如何只保留年份和月份。通过设置日期部分为1号,时间部分为0,我们可以忽略具体的日期和时间,只关心年份和月份的值。