今天七月二十八日,2022年星期四,
我想在七月之前的最后几个月拿到最后六个月
我想在七月前的12个月前拿到las。
我已经尝试了6个月了
var d = new Date();
const month= d.setDate(d.getDate() - 180).getMonth()
console.log(month)
我需要短信,小君,梅等等。
发布于 2022-07-29 02:27:12
Intl.DateTimeFormat
可用于创建日期格式化程序,它将根据您的喜好生成本地化的月份名称。关于使用默认的区域设置,构造函数文档会这样说:
若要使用浏览器的默认区域设置,请传递一个空数组。
在下面的示例中,我选择了{month: "short"}
格式(基于您问题中的预期输出),但是您可以根据您的喜好更改选项。
然后创建输入日期的副本,并每次减去一个月,以创建目标月份名称。以下是一个实用的解决方案:
'use strict';
/** Wraps a (potentially-negative) integer to a positive value less than the ceiling */
function uInt (ceil, n) {
while (n < 0) n += ceil;
return n % ceil;
}
function getPreviousNMonths (n, date = new Date()) {
// Create a copy of the input date to keep the function pure
const d = new Date(date.getTime());
const formatter = new Intl.DateTimeFormat([], {month: 'short'});
const names = [];
for (let i = 0; i < n; i += 1) {
const monthIndex = uInt(12, d.getMonth() - 1);
d.setMonth(monthIndex);
names.push(formatter.format(d));
}
return names;
}
// Use:
// Initialize a date
const date = new Date(0);
// Adjust the date to the local date according to the details in your question
date.setFullYear(2022);
date.setMonth(6);
date.setDate(28);
const previous6MonthNames = getPreviousNMonths(6, date);
const previous12MonthNames = getPreviousNMonths(12, date);
console.log({previous6MonthNames, previous12MonthNames});
发布于 2022-07-29 02:18:26
您可以使用setMonth和toLocaleString来获取文本中的月份名称。
var d = new Date();
d.setMonth(d.getMonth() - 6)
console.log(d.toLocaleString('default', {month: 'short'}))
发布于 2022-07-29 02:12:54
日历有一个套餐:
import moment from 'moment';
moment().add(10, 'days').calendar(); // use this to add days, months or year in add parameter.
https://stackoverflow.com/questions/73160887
复制相似问题