Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get friday from week number and year in javascript

I have week number and year, need to find out date (friday) in that week and year.

function getFriday(week_num, year)
{
    ?

    return friday_date_object;
}

How do I do that?

like image 554
Peter Avatar asked Dec 29 '10 15:12

Peter


3 Answers

The week #1 is the week with the first Thursday.

Here is a function to get any day:

var w2date = function(year, wn, dayNb){
    var j10 = new Date( year,0,10,12,0,0),
        j4 = new Date( year,0,4,12,0,0),
        mon1 = j4.getTime() - j10.getDay() * 86400000;
    return new Date(mon1 + ((wn - 1)  * 7  + dayNb) * 86400000);
};
console.log(w2date(2010, 1, 4));

week numbers start at 1 until 52 or 53 it depends the year.
For the day numbers, 0 is Monday, 1 is Tuesday, ... and 4 is Friday

like image 112
Mic Avatar answered Oct 16 '22 18:10

Mic


Use the date.js library. It's great for all date-related functions.

like image 1
Diodeus - James MacFarlane Avatar answered Oct 16 '22 20:10

Diodeus - James MacFarlane


Here's some quick code

var DAY = 86400000;

function getFriday(weekNum, year) {
  var year = new Date(year.toString()); // toString first so it parses correctly year numbers
  var daysToFriday = (5 - year.getDay()); // Note that this can be also negative
  var fridayOfFirstWeek = new Date(year.getTime() + daysToFriday * DAY);
  var nthFriday = new Date(fridayOfFirstWeek.getTime() + (7 * (weekNum - 1) * DAY));
  return nthFriday;
}

Split some variables for readability.

But if you find yourself writing more complex time operations, you're better using a library instead.

like image 1
Chubas Avatar answered Oct 16 '22 18:10

Chubas