如何通过js获得一个月的4个星期一? [英] How to get the 4 monday of a month with js?

查看:1015
本文介绍了如何通过js获得一个月的4个星期一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(首先,请原谅我的英文,我是初学者)



让我解释一下情况:



我想使用Google图表工具创建图表(尝试一下,这非常有用)。
这部分不是很难...



问题出现在我有一个特定的图表要求在x轴一个月的四个星期:我想在屏幕上只显示今天的四个星期。



我已经拥有currentMonth和currentYear变量,我知道如何获得第一天的月份。所有我需要的是如何获得一个月的四个星期,在一个阵列。所有这一切都在同一个JavaScript文件中。



我在编程逻辑中很迷失,我看到很多解决方案不适合我的情况。 / p>

所以,我有什么是:

  var date = new日期(); 
var currentYear = date.getFullYear();
var currentMonth = date.getMonth();
var firstDayofMonth = new Date(currentYear,currentMonth,1);
var firstWeekDay = firstDayofMonth.getDay();

我想要这样:

  var myDates = 
[new Date(firstMonday),new Date(secondMonday),new Date(thirdMonday),new Date(FourthMonday)]

感谢您阅读,如果可以帮助我...:)



Gaelle

解决方案

以下函数将返回所有当月的星期一:

  function getMondays(){
var d = new Date(),
month = d.getMonth(),
mondays = [];

d.setDate(1);

//获取本月的第一个星期一
while(d.getDay()!== 1){
d.setDate(d.getDate()+ 1) ;
}

//获取月中所有其他星期一
while(d.getMonth()===月){
mondays.push(new Date (d.getTime()));
d.setDate(d.getDate()+ 7);
}

返回星期一;
}


(first of all, excuse my english, i'm a beginner)

let me explain the situation :

I would like to create charts using Google Charts Tool (give it a try, it's very helpful). This part is not really difficult...

The problem comes when i have a specific chart requiring in the x-axis the four weeks of a month : i would like to display on the screen only the four mondays in the currentmonth.

I already have got the currentMonth and the currentYear variables and i know how to get the first day of the month. all i need is how to get the four mondays of a month, in an array. And all of this in the same JavaScript file.

I'm pretty lost within my programming logic, and i've seen plenty of solutions wich fit not my case.

so, what do i have is :

var date = new Date();
var currentYear = date.getFullYear();
var currentMonth = date.getMonth();
var firstDayofMonth = new Date(currentYear,currentMonth,1);
var firstWeekDay = firstDayofMonth.getDay();

and i would like to have something like this :

var myDates =
[new Date(firstMonday),new Date(secondMonday), new Date(thirdMonday),new Date(fourthMonday)]

Thank you for reading, and if you could help me... :)

Gaelle

解决方案

The following function will return all Mondays for the current month:

function getMondays() {
    var d = new Date(),
        month = d.getMonth(),
        mondays = [];

    d.setDate(1);

    // Get the first Monday in the month
    while (d.getDay() !== 1) {
        d.setDate(d.getDate() + 1);
    }

    // Get all the other Mondays in the month
    while (d.getMonth() === month) {
        mondays.push(new Date(d.getTime()));
        d.setDate(d.getDate() + 7);
    }

    return mondays;
}

这篇关于如何通过js获得一个月的4个星期一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆