我正试图形成一个日期,这是3个月前的当前日期。我通过下面的代码得到当前月份
var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;
你能给我提供一个逻辑来计算和形成一个日期(date数据类型的对象),考虑到当月份是一月(1)时,日期前3个月将是十月(10)吗?
我正试图形成一个日期,这是3个月前的当前日期。我通过下面的代码得到当前月份
var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;
你能给我提供一个逻辑来计算和形成一个日期(date数据类型的对象),考虑到当月份是一月(1)时,日期前3个月将是十月(10)吗?
当前回答
var todayDate =新日期。slice (0) (10); var d =新日期(todayDate); d . setMonth (d . getMonth () - 3); 游戏机。log (todayDate) log (d . toISOString(游戏机)。slice (0) (10));
其他回答
直接放入变量中的“一行代码”(多行代码,便于阅读):
var oneMonthAgo = new Date(
new Date().getFullYear(),
new Date().getMonth() - 1,
new Date().getDate()
);
对于今天之前三个月的获取日期:
let d = new Date(new Date().setMonth(new Date().getMonth() - 3))
console.log(d.toISOString().slice(0, 10))
// 2022-05-24 (today is 2022-08-24)
var todayDate =新日期。slice (0) (10); var d =新日期(todayDate); d . setMonth (d . getMonth () - 3); 游戏机。log (todayDate) log (d . toISOString(游戏机)。slice (0) (10));
传递一个JS Date对象和一个你想加/减多少个月的整数。monthsToAdd可以是正的也可以是负的。返回一个JS日期对象。
如果您的originalDateObject是3月31日,并且您传递-1作为monthsToAdd,那么您的输出日期将是2月28日。
如果您经过了大量的月份,比如36个月,它也会正确地处理年份调整。
const addMonthsToDate = (originalDateObject, monthsToAdd) => {
const originalDay = originalDateObject.getUTCDate();
const originalMonth = originalDateObject.getUTCMonth();
const originalYear = originalDateObject.getUTCFullYear();
const monthDayCountMap = {
"0": 31,
"1": 28,
"2": 31,
"3": 30,
"4": 31,
"5": 30,
"6": 31,
"7": 31,
"8": 30,
"9": 31,
"10": 30,
"11": 31
};
let newMonth;
if (newMonth > -1) {
newMonth = (((originalMonth + monthsToAdd) % 12)).toString();
} else {
const delta = (monthsToAdd * -1) % 12;
newMonth = originalMonth - delta < 0 ? (12+originalMonth) - delta : originalMonth - delta;
}
let newDay;
if (originalDay > monthDayCountMap[newMonth]) {
newDay = monthDayCountMap[newMonth].toString();
} else {
newDay = originalDay.toString();
}
newMonth = (+newMonth + 1).toString();
if (newMonth.length === 1) {
newMonth = '0' + newMonth;
}
if (newDay.length === 1) {
newDay = '0' + newDay;
}
if (monthsToAdd <= 0) {
monthsToAdd -= 11;
}
let newYear = (~~((originalMonth + monthsToAdd) / 12)) + originalYear;
let newTime = originalDateObject.toISOString().slice(10, 24);
const newDateISOString = `${newYear}-${newMonth}-${newDay}${newTime}`;
return new Date(newDateISOString);
};
var日期= . getelementbyid(“日期”); var d = new Date(); 文档。写(d + "<br/>"); d.setMonth(d.getMonth() - 6); document . write (d); 如果(d <日期) 文档。写作(“少于6个月”); 其他的 文档。写(“大于6个月”);