lolol
lolol

Reputation: 4390

Datejs: get the day number of the week

Using Datejs - Get the day of the week

I'm also using http://www.datejs.com. And I also must be missing it. Is there a way I can have the day number of the week?

I know I can use an array equivalence, but the library is so good that I think I'm missing it, and I looked everywhere.

UPDATE:

I also know I can use the date getDay method, but I think there is a datejs alternative to correct some weird behavior of the built in date object.

Upvotes: 0

Views: 902

Answers (3)

This code calculates the day of the week for dates after 1700/1/1 through one of the algorithms that exist to calculate it

var weekDay = function(year, month, day) {
                  var offset = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
                  var week   = {0:'Sunday', 
                                1:'Monday', 
                                2:'Tuesday', 
                                3:'Wednesday', 
                                4:'Thursday', 
                                5:'Friday', 
                                6:'Saturday'};
                  var afterFeb = (month > 2)? 0 : 1;
                  aux = year - 1700 - afterFeb;
                  // dayOfWeek for 1700/1/1 = 5, Friday
                  dayOfWeek  = 5;                      
                  // partial sum of days betweem current date and 1700/1/1
                  dayOfWeek += (aux + afterFeb) * 365;
                  // leap year correction
                  dayOfWeek += parseInt(aux / 4) - 
                               parseInt(aux / 100) + 
                               parseInt((aux + 100) / 400);
                  // sum monthly and day offsets
                  dayOfWeek += offset[month - 1] + (day - 1);
                  dayOfWeek = parseInt(dayOfWeek % 7);

                  return [dayOfWeek, week[dayOfWeek]];
              };  


console.log(weekDay(2013, 6, 15)[0] == 6, weekDay(2013, 6, 15)[1] == "Saturday");
console.log(weekDay(1969, 7, 20)[0] == 0, weekDay(1969, 7, 20)[1] == "Sunday");
console.log(weekDay(1945, 4, 30)[0] == 1, weekDay(1945, 4, 30)[1] == "Monday");
console.log(weekDay(1900, 1, 1)[0]  == 1,  weekDay(1900, 1, 1)[1] == "Monday");
console.log(weekDay(1789, 7, 14)[0] == 2, weekDay(1789, 7, 14)[1] == "Tuesday"); 

Upvotes: 0

jbabey
jbabey

Reputation: 46647

just use the built in getDay function on the Date object:

new Date().getDay();

Upvotes: 1

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123473

You can get the number with the standard Date methods, getDay or getUTCday:

new Date('2012-10-03').getDay(); // 2

Upvotes: 1

Related Questions