在 Javascript 中获取一周中的天数,一周从星期日开始

编程入门 行业动态 更新时间:2024-10-24 05:21:35
本文介绍了在 Javascript 中获取一周中的天数,一周从星期日开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是来自用户的给定输入:

Here's the given input from the user:

年 = 2011,月 = 3(三月),周 = 2

Year = 2011, Month = 3 (March), Week = 2

我想用 JavaScript 获取 2011 年 3 月第 2 周的天数.

I want to get the days in week 2 of March 2011 in JavaScript.

例如6日星期日、7日星期一、8日星期二、9日星期三、10日星期四、11日星期五、12日星期六

e.g. Sunday 6th, Monday 7th, Tuesday 8th, Wednesday 9th, Thursday 10th, Friday 11th, Saturday 12th

有什么想法吗?谢谢!

推荐答案

Given

var year = 2011; var month = 3; var week = 2;

var firstDateOfMonth = new Date(year, month - 1, 1); // Date: year-month-01 var firstDayOfMonth = firstDateOfMonth.getDay(); // 0 (Sun) to 6 (Sat) var firstDateOfWeek = new Date(firstDateOfMonth); // copy firstDateOfMonth firstDateOfWeek.setDate( // move the Date object firstDateOfWeek.getDate() + // forward by the number of (firstDayOfMonth ? 7 - firstDayOfMonth : 0) // days needed to go to ); // Sunday, if necessary firstDateOfWeek.setDate( // move the Date object firstDateOfWeek.getDate() + // forward by the number of 7 * (week - 1) // weeks required (week - 1) ); var dateNumbersOfMonthOnWeek = []; // output array of date #s var datesOfMonthOnWeek = []; // output array of Dates for (var i = 0; i < 7; i++) { // for seven days... dateNumbersOfMonthOnWeek.push( // push the date number on firstDateOfWeek.getDate()); // the end of the array datesOfMonthOnWeek.push( // push the date object on new Date(+firstDateOfWeek)); // the end of the array firstDateOfWeek.setDate( firstDateOfWeek.getDate() + 1); // move to the next day }

然后

  • dateNumbersOfMonthOnWeek 将包含该周的日期编号.
  • datesOfMonthOnWeek 将包含该周的日期对象.
  • 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.

更多推荐

在 Javascript 中获取一周中的天数,一周从星期日开始

本文发布于:2023-11-27 05:17:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636756.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:天数   星期日   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!