用 Javascript 获取一周中的天数,一周从周日开始
以下是用户给出的输入:
年 = 2011 年,月 = 3(三月),周 = 2
我想在 JavaScript 中获取 2011 年 3 月第 2 周的天数。
例如,周日 6 号、周一 7 号、周二 8 号、周三 9 号、周四 10 号、周五 11 号、周六 12 号
有什么想法吗?谢谢!
Here's the given input from the user:
Year = 2011, Month = 3 (March), Week = 2
I want to get the days in week 2 of March 2011 in JavaScript.
e.g. Sunday 6th, Monday 7th, Tuesday 8th, Wednesday 9th, Thursday 10th, Friday 11th, Saturday 12th
Any ideas? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
dateNumbersOfMonthOnWeek
给定然后
datesOfMonthOnWeek
将包含该周的日期对象。虽然这对于这项工作来说似乎有点大材小用,但要使其在所有情况下都有效,例如当日期数字跨越到另一个月份时,需要做很多工作。不过,我确信它可以优化得不那么冗长。
Given
and
then
dateNumbersOfMonthOnWeek
will have the date numbers of that week.datesOfMonthOnWeek
will have the date objects of that week.While this may seem like it is overkill for the job, much of this is required to make it work in all situations, like when the date numbers cross over to another month. I'm sure it could be optimised to be less verbose, though.
我通常使用 Datejs 在 js 中进行日期操作。我会这样做:
I normally use Datejs for date manipulations in js. I'd do it like this:
假设该月的第一周是该月的第一周,则以下函数将返回给定年、月和周数的该周第一天的日期:
获取其余天数,只需循环6次,每次在日期上加1,例如
Assuming that the first week of the month is the one with the first of the month in it, then the following function will return the date of the first day of the week given year, month and week number:
To get the rest of the days, just loop 6 times adding one to the date each time, e.g.
对第一个对我有用的答案进行一些修改:
A little modification of the first answer that worked for me: