gpt4 book ai didi

javascript - 获取 "last monday of may"的最佳方式

转载 作者:行者123 更新时间:2023-11-28 09:17:15 24 4
gpt4 key购买 nike

使用 javascript 获取五月最后一个星期一的最佳方式是什么?我知道我可以得到该月的最后一天,然后他们减去我想要的日子的天数之差。但是,有一种简短、更优雅、更高效的方法吗?

谢谢

最佳答案

function getLastMonday(month, year) {
var d = new Date();
if (year) { d.setFullYear(year); }
d.setDate(1); // Roll to the first day of ...
d.setMonth(month || d.getMonth() + 1); // ... the next month.
do { // Roll the days backwards until Monday.
d.setDate(d.getDate() - 1);
} while (d.getDay() !== 1);
return d;
}

getLastMonday(); // => Mon Mar 25 2013 12:44:39 GMT-0600 (MDT)
getLastMonday(5); // => Mon May 27 2013 12:41:52 GMT-0600 (MDT)
getLastMonday(1, 2000); // => Mon Jan 31 2000 12:43:15 GMT-0700 (MST)

关于javascript - 获取 "last monday of may"的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15507352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com