Luxon如何将日期设置为一个月中的上一个星期一?

huangapple go评论56阅读模式
英文:

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: &quot;long&quot;,year: &quot;numeric&quot;,month: &quot;long&quot;,
                day: &quot;numeric&quot;};

[2018,2019,2020,2021,2022,2023,2024,2025].forEach(y=&gt;
  console.log(getLastMondayOfMay(y).toLocaleString(&#39;en-EN&#39;,options)))

<!-- end snippet -->

答案2

得分: 0

DateTime.now().set({ month: 5 }).endOf('month').startOf('week');

根据我的理解,Luxon 的一周总是从星期一开始,因此在获取五月份的月底后请求一周的开始应该得到五月的最后一个星期一(如果您的起始点是 DateTime.now(),则为当前年份)。

英文:
DateTime.now().set({ month: 5 }).endOf(&#39;month&#39;).startOf(&#39;week&#39;);

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()).

huangapple
  • 本文由 发表于 2023年7月18日 04:01:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定