-2

I have this Javascript code:

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;

var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm}

today = dd+'/'+mm;
document.write(today);

Now the months are in mm, so mumbers, I want them to display in words. Now I am not a javescript genius, actually a noob, but my logical mind thought of this:

if(mm = 1){mm = 'January'} 

Now as I was already expecting, that doesn't work.

Is there a way to transform the numbers in words with this code, or should I look for another way?

Johan
  • 361
  • 2
  • 7
  • 16

2 Answers2

2

Make an array or object of month names like this:

var months = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];

Then just get the month you need like this:

mm = months[mm - 1];

-1 is because JS is zero-based, so January is at index 0, February at 1, etc.

Also, like GolezTrol said, your approach is fine, you just need to use the comparison operator (==) instead of assignment operator (=) in your if-clause.

Shomz
  • 37,421
  • 4
  • 57
  • 85
  • 1
    no, you don't need the `-1`. January is 0, February is 1, etc. – tckmn Nov 12 '13 at 13:15
  • 1
    @Doorknob: in the question `mm` was defined as `new Date().getMonth() + 1`, so technically this is correct - though there's no _real_ point in doing something which is redundant. – Qantas 94 Heavy Nov 12 '13 at 13:16
  • @Doorknob, yes but, in the question it says if mm == 1, mm is January. – Shomz Nov 12 '13 at 13:16
  • 1
    @Qantas94Heavy Hm, it was, but why add one and then subtract one? Just keep the original value... – tckmn Nov 12 '13 at 13:16
  • Judging by all that, it might be a good idea to even go with `(mm - 1) % 12`, just in case... – Shomz Nov 12 '13 at 13:22
  • Thanks worked, I erased the `+1` in the original code and the `- 1` from your answer and that worked as well. – Johan Nov 12 '13 at 13:24
  • Great, glad it helped! Also, to show code in the comments you need to use backtick (`) like this: backtick Your_code_here backtick (no spaces needed). – Shomz Nov 12 '13 at 13:26
1

if(mm == 1){mm = 'January'} would work better. The problem is the single =, which isn't a comparison operator and should be double ==. This is the actual error in your code.

You could write it a bit easier/more readable though, by using an array as @Shomz already suggested. Or for other cases like this, a switch might help you out:

switch (mm) {
  case 1: return 'January'; break;
  case 2: return 'February'; break;
  case 3: return 'March'; break;
  case 4: return 'April'; break;
  ...
}

http://www.javascriptkit.com/javatutors/switch.shtml

In this case, though, the array solution is the easiest.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210