Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get first and last day of a specific calendar week in JavaScript? [duplicate]

Tags:

javascript

I need to get the first and last day of a specific calendar week in JavaScript. I want to pass week and year to a function. I am thinking about a function who looks like this one.

    getBeginEndOfCalweek: function(ww, yyyy) { 

?
    return beginEnd [ yyyy-mm-dd , yyyy-mm-dd] 
    }

I want to call that function with a specific week and year. Like this.

var a[] = getBeginEndOfCalweek(48,2017);

Every help is very much appreciated. Best Peter

like image 793
Peter S. Avatar asked Feb 01 '26 02:02

Peter S.


1 Answers

I use the function of an other Peter in this Answer

// Function from https://stackoverflow.com/users/2881466/peter
// https://stackoverflow.com/a/19375264/5413817
function firstDayOfWeek (week, year) {

    // Jan 1 of 'year'
    var d = new Date(year, 0, 1),
        offset = d.getTimezoneOffset();

    // ISO: week 1 is the one with the year's first Thursday 
    // so nearest Thursday: current date + 4 - current day number
    // Sunday is converted from 0 to 7
    d.setDate(d.getDate() + 4 - (d.getDay() || 7));

    // 7 days * (week - overlapping first week)
    d.setTime(d.getTime() + 7 * 24 * 60 * 60 * 1000 
        * (week + (year == d.getFullYear() ? -1 : 0 )));

    // daylight savings fix
    d.setTime(d.getTime() 
        + (d.getTimezoneOffset() - offset) * 60 * 1000);

    // back to Monday (from Thursday)
    d.setDate(d.getDate() - 3);

    return d;
}

function getBeginEndOfCalweek(week, year) { 
  var result = {
        'start': new Date(),
        'end': new Date(),

    'toString': function(){
        return 'start: '+this.start+'<br>end: '+this.end;
    }
  };
  result.start = firstDayOfWeek(week, year);
  result.end.setDate(result.start.getDate() + 6)

  return result; 
}

console.log(getBeginEndOfCalweek(48,2017).toString());

This will output (in Germany):

start: Mon Nov 27 2017 00:00:00 GMT+0100 (Mitteleuropäische Zeit)
end: Sun Dec 03 2017 12:13:22 GMT+0100 (Mitteleuropäische Zeit)
like image 186
Marcus Avatar answered Feb 03 '26 19:02

Marcus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!