X Monday of the Month - struggling

28 views
Skip to first unread message

Peter Scargill

unread,
Nov 6, 2016, 1:31:22 AM11/6/16
to nodejs
Can someone give me a hand...

I need a simple function, given a day of the week - and a number, to do queries like "is this the 3rd Monday of the month" - returning true or false.

I thought I had it here but it is returning false regardless. Can anyone spot what's wrong?

function dayinmonth(weekday,n)
{
    var date=new Date();
        if (n > 0)
        {
            var first = new Date(date.Year, date.Month, 1);
            return ((date.Day - first.Day)/ 7 == n - 1) && (date.DayOfWeek == weekday);

        }
        else
        {
            var last = new Date(date.Year, date.Month, 1).AddMonths(1).AddDays(-1);
            return ((last.Day - date.Day) / 7 == (Math.Abs(n) - 1)) && (date.DayOfWeek == weekday);
        } 
}

shufan

unread,
Dec 1, 2016, 11:07:03 AM12/1/16
to nodejs
Peter,

I'm not sure `Date` class in EScript have Day DayOfWeek properties.

but based on your requiement I did this, a little augly but works:


function dayInMonth(date, weekday, n) {
    var day = date.getDay();

    if (day !== weekday) {
        return false;
    }

    var preMonthLast = new Date(new Date().setTime(date.getTime() - n * 7 * 86400000));
    var first = new Date(new Date().setTime(date.getTime() - (n - 1) * 7 * 86400000));
    if (date.getMonth() - preMonthLast.getMonth() === 1 ||
        (date.getMonth() === 0 && preMonthLast.getMonth() === 11)) {
        if (date.getMonth() === first.getMonth()) {
            return true;
        }
    }

    return false;
}

console.log(dayInMonth(new Date('2016-12-01T00:00:01'), 4, 1));
console.log(dayInMonth(new Date('2016-12-02T00:00:01'), 5, 1));
console.log(dayInMonth(new Date('2016-12-08T00:00:01'), 4, 2));

console.log(dayInMonth(new Date('2017-01-03T00:00:01'), 2, 1));
console.log(dayInMonth(new Date('2017-01-03T00:00:01'), 2, 2));
Reply all
Reply to author
Forward
0 new messages