Javascript - 获取当前日期和月底之间的星期日数

发布于 2024-12-04 11:00:16 字数 121 浏览 0 评论 0原文

我怎样才能知道从现在到月底有多少个星期日?我对 JS 日期对象不太有经验,所以我不知道从哪里开始。我可以循环遍历现在到月底之间的日子,并检查这一天是否是星期日,但这只是最坏情况的解决方案。

有人对此有任何想法吗?

How can I get how many Sundays there are between now and the end of the month? I'm not really experienced with JS date objects, so I don't know where to start. I could loop through the days between now and the end of the month and check if the day is Sunday, but that would be only a worst-case solution.

Anyone got any idea about this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ぽ尐不点ル 2024-12-11 11:00:17

如果只是从现在到月底,最坏的情况是 O(31),这非常多,你可以说它和 O(1) 一样快。小的优化可以通过找到第一个星期日然后添加 7 几次直到它通过或等于 28 来完成,计算“几次”+ 1(对于第一个星期日),您就得到了星期日的数量。最坏的情况现在约为 O(10),查找第一个星期日的 O(7),循环的 O(3)。但说实话,你想这样做吗?

注意:也许我有点错误地计算了复杂性,但它是围绕这些数字的。

If it's only from now and end of the month, the worst case if only O(31) which is VERY MUCH you can say it's as fast as O(1). The small optimization could be done by finding the first sunday then add 7 a couple of times until it passes or equals to 28, count that "couple of times" + 1 (for the first sunday) and you get the number of sundays. The worst case is now around O(10), O(7) for finding the first sunday, O(3) for the loop. But really, do you want to do this?

NOTE: maybe I miscount the complexity a little, but it's around those numbers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文