如何在JavaScript中查找任何给定工作日的序号位置

时间:2015-01-27 02:14:47

标签: javascript date

我试图在不变的时间内找到工作日的实际位置。我得到它循环,但试图用一些数学找出它。我知道这就像分为7但不能让它发挥作用。

这是代码。

for(var ind=0; ind<=between.length; ind++){
   if (new Date(between[ind]).getMonthWeek() === baseDtWk && new Date(between[ind]).getDay() === baseDtD) {
       datesToBeMarked.push(between[ind]);
       console.log(" :Date: " + between[ind] + " :Week: " + new Date(between[ind]).getMonthWeek());
       console.log("Date entered : " + new Date(between[ind]));
   }

}

2 个答案:

答案 0 :(得分:1)

我这几天回来了。它就像下面的代码一样简单。 :)

On fiddle.

Number.prototype.nth= function(){
    var n= Math.round(this), t= Math.abs(n%100), i= t%10;
    if(i<4 && (t<4 || t> 20)){
        switch(i){
            case 1:return n+'st';
            case 2:return n+'nd';
            case 3:return n+'rd';
        }
    }
    return n+'th';
}
Date.prototype.nthofMonth= function(){
    var today= this.getDate(),m=this.getMonth(),
    day= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
    'Friday', 'Saturday'][this.getDay()],
    month= ['January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'][m];
    return [(m+1)+'-'+today,'the ', Math.ceil(today/7).nth(), day, 'of', month, 'in', this.getFullYear()].join(' ');
}

var date=new Date().nthofMonth();
console.log(date);

答案 1 :(得分:0)

你还没有展示你想要的结果,我想你想知道某个特定的日期是否是,例如,第n个星期二,例如。

// Add ordinal to a number
function addOrdinal(n) {
    var ord = [,'st','nd','rd'];
    var a = n % 100;
    return n + (ord[a>20? a%10 : a] || 'th');
}

// Return the ordinal number of a day in the month
function ordinalDay(d) {
  d = d || new Date();
  var days = ['Sunday','Monday','Tuesday','Wednesday',
              'Thursday', 'Friday','Saturday'];
  return addOrdinal(Math.ceil(d.getDate()/7)) + ' ' + days[d.getDay()];
}

console.log(ordinalDay(new Date(2015,0,1)));   // 1st Thursday
console.log(ordinalDay(new Date(2015,0,27)));  // 4th Tuesday
console.log(ordinalDay(new Date(2015,0,31)));  // 5th Saturday
console.log(ordinalDay(new Date(2015,11,25))); // 4th Friday