Search code examples
javascriptdatemootoolsweekday

MooTools: Get the first and last days of a given week


I'm relatively inexperienced in JavaScript (we're using MooTools, here) and I'm stuck with a problem:

Is there a quick way to get the first and last dates of a given week? e.g. week 17 / 2015 starts on Monday, April 20th and ends on Sunday, April 26th.

My goal is to find out if a given week starts and ends in the same month (week 18 wont, since it starts on April 27th and ends on May 3rd).

Many thanks on any help with examples or pointing me to the right documentation. I've been looking for a while and haven't found anything like this, and I find MooTools documentation very poor...


Solution

  • Boa noite Filipe,

    to do this you do not need MooTools. You can do with Vanilla JS.

    Here is an idea:

    function dayAnalizer(str) {
        var date = new Date(str).getTime();
        var weekAfter = date + 7 * 24 * 60 * 60 * 1000;
        return new Date(date).getMonth() == new Date(weekAfter).getMonth();
    }
    
    console.log(dayAnalizer('10-05-2015')); // true
    console.log(dayAnalizer('13-05-2015')); // false
    console.log(dayAnalizer('16-05-2015')); // false
    

    jsFiddle: http://jsfiddle.net/1g4bvgjg/

    basically it gets a date in string format and converts it to timestamp (miliseconds), then create another date 1 week forward. In the end compare if both have same month.

    If you need to know if a certain week in a year starts and ends in the same month you could use something like this:

    function weekAnalyser(week, year) {
        var days = (1 + (week - 1) * 7); // 1st of January + 7 days for each week
        var date = new Date(year, 0, days);
        var dayOfWeek = date.getDay(); // get week day
        var firstDayOfWeek = date.getTime() - (dayOfWeek) * 60 * 60 * 24 * 1000); // rewind to 1st day of week
        var endOfWeek = firstDayOfWeek + 6 * 24 * 60 * 60 * 1000;
        return new Date(firstDayOfWeek).getMonth() == new Date(endOfWeek).getMonth();
    }
    

    jsFiddle: http://jsfiddle.net/zfassz29/


    Ps. Welcome to Portuguese Stackoverflow: https://pt.stackoverflow.com/