我得到一个格式化的日期:
18th February
在添加周数后,应该以相同的格式返回例子:
input => 18th February + 7 weeks:
output => 31st March
我可以获得日期并添加周数,但我发现将日期格式化非常复杂。
这是我现在的记录:
let date = new Date(("18th February").replace(/st|rd|nd|th/g, ""))
let weeks = 7 * 7
let newDate = date.setDate(date.getDate() + weeks)
console.log(new Date(newDate))
//Output
2001-03-31T23:00:00.000Z
//Desire Output
//31st March
谢谢你的帮助。
我认为前端的日期格式不是很好,所以库总是有帮助的(比如momentjs, datefnz等)
但是你可以把这个添加到你的代码中使它工作:
let date = new Date(("18th February").replace(/st|rd|nd|th/g, ""))
let weeks = 7 * 7
let newDate = new Date(date.setDate(date.getDate() + weeks))
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
let month = months[newDate.getMonth()]
let day = newDate.getDate()
function dayWithNth (d) {
if (d > 3 && d < 21) return `${d}th`;
switch (d % 10) {
case 1: return `${d}st`;
case 2: return `${d}nd`;
case 3: return `${d}rd`;
default: return `${d}th`;
}
}
console.log(`${dayWithNth(day)} ${month}`)