英文:
Luxon how to set date to last monday of a month?
问题
我正在尝试在Luxon中定义节假日,比如五月的最后一个星期一,我该如何生成一个Luxon日期对象:
DateTime.now().set({ month: 5, weekday: 1 })
在Luxon中有没有一种方法可以指定上个星期,而不需要知道确切的日期?
英文:
I'm trying to define holidays in Luxon, such as memorial day which is the last Monday of May. How can I generate a luxon date object with this:
DateTime.now().set({ month: 5, weekday: 1 })
Is there a way to specify last week in Luxon without knowing the exact date?
答案1
得分: 1
function getLastMondayOfMay(y){
const dd = new Date(y, 4, 31), wd = dd.getDay(); // set date to last day of May and get weekday
dd.setDate(31 - (wd + 7 - 1) % 7); // find the closest Monday before that
return dd;
}
const options = { weekday: "long", year: "numeric", month: "long", day: "numeric" };
[2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025].forEach(y =>
console.log(getLastMondayOfMay(y).toLocaleString('en-EN', options)))
英文:
You can, of course also do it without Luxon by using some basic Date
functionality:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function getLastMondayOfMay(y){
const dd=new Date(y,4,31), wd=dd.getDay(); // set date to last day of May and get weekday
dd.setDate(31-(wd+7-1)%7); // find the closest Monday before that
return dd;
}
const options = {weekday: "long",year: "numeric",month: "long",
day: "numeric"};
[2018,2019,2020,2021,2022,2023,2024,2025].forEach(y=>
console.log(getLastMondayOfMay(y).toLocaleString('en-EN',options)))
<!-- end snippet -->
答案2
得分: 0
DateTime.now().set({ month: 5 }).endOf('month').startOf('week');
根据我的理解,Luxon 的一周总是从星期一开始,因此在获取五月份的月底后请求一周的开始应该得到五月的最后一个星期一(如果您的起始点是 DateTime.now(),则为当前年份)。
英文:
DateTime.now().set({ month: 5 }).endOf('month').startOf('week');
From my understanding, Luxon's weeks always start on Monday, so asking for the start of the week after getting the end of the month of May should get you the last Monday of May (of the current year if your starting point is DateTime.now()
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论