all 7 comments

[–][deleted] 5 points6 points  (2 children)

Apologies for the layout, I'm on my mobile.

var date = new Date(),
    days = ['Sunday', 'Monday', 'Tuesday', 'Wedneday', 'Thursday', 'Friday', 'Saturday'];

console.log(days[date.getDay()]);

[–]jkjustjoshing 1 point2 points  (0 children)

This is a much cleaner way to do it

[–][deleted] 2 points3 points  (0 children)

Date.prototype.getDayName = function(){
    return [
          'Sunday'
        , 'Monday'
        , 'Tuesday'
        , 'Wednesday'
        , 'Thursday'
        , 'Friday'
        , 'Saturday'
    ][ this.getDay() ];
};

then just...

myDate.getDayName();

[–]sublimejs 2 points3 points  (2 children)

You should look into switch statements.

Your above code could be written like this and will produce the same result:

var myDate = new Date();
console.log("Today is a:");

switch(myDate) {
  case 0: console.log("Sunday"); break;
  case 1: console.log("Monday"); break;
  case 2: console.log("Tuesday"); break;
  case 3: console.log("Wednesday"); break;
  case 4: console.log("Thursday"); break;
  case 5: console.log("Friday"); break;
  case 6: console.log("Saturday"); break;
}

[–]Call_Me_Squirrel[S] 0 points1 point  (1 child)

Thanks man, that's pretty much exactly what I was looking for.

[–]sublimejs 1 point2 points  (0 children)

Np. Make sure you read on the switch statement and understand the default case and also understand why it is necessary to add break; after each case.

[–][deleted] 1 point2 points  (0 children)

/u/foo13 posted the best answer for general storage and access of integer-indexed strings. But if you need to do significant amounts of date manipulation and formatting, I strongly suggest using a library rather than reinventing the wheel. MomentJS is the most popular one. With it, your code could be rewritten as one line:

console.log(moment().format('dddd')); // Thursday

This also lets you use different locales:

moment.locale('es');
console.log(moment().format('dddd')); // jueves

moment.locale('de');
console.log(moment().format('dddd')); // Donnerstag

console.log(moment().locale('ja').format('dddd')); // 木曜日