Javascript - 获取当前日期和月底之间的星期日数
我怎样才能知道从现在到月底有多少个星期日?我对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果只是从现在到月底,最坏的情况是 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.