lundi 30 mars 2015

Javascript - Parsing toDateString Month from a text string to number string using "IF(){}" vs "SWITCH(){}

I have what is probably a very simple question about using IF statements vs SWITCH in Javascript. I am attempting to add the current date to my page in the format "Month/Day/Year" where "Month" is a number like so "03/30/2015". I have been able to solve this problem using the code below: http://ift.tt/1HYeHez



var d = new Date();
var dd = d.toDateString();
var ddd = dd.split(' ');
ddd.shift();
var mon = ddd[0];
var da = ddd[1];
var yr =ddd[2];
if (mon == "Jan"){monb = 1;}
if (mon == "Feb"){monb = 2;}
if (mon == "Mar"){monb = 3;}
if (mon == "Apr"){monb = 4;}
if (mon == "May"){monb = 5;}
if (mon == "Jun"){monb = 6;}
if (mon == "Jul"){monb = 7;}
if (mon == "Aug"){monb = 8;}
if (mon == "Sep"){monb = 9;}
if (mon == "Oct"){monb = 10;}
if (mon == "Nov"){monb = 11;}
if (mon == "Dec"){monb = 12;}
slashDate = monb + "/" + da + "/" + yr;
document.getElementById('titleDate').innerHTML = slashDate;


However, my understanding is that it would be better to use a SWITCH statement here. So I have replaced the lengthy IF statements with a SWITCH statement as shown here: http://ift.tt/1HYeJ6f



var d = new Date();
var dd = d.toDateString();
var ddd = dd.split(' ');
ddd.shift();
var mon = ddd[0];
var da = ddd[1];
var yr =ddd[2];
switch(mon){
case "Jan": monb = 01;
case "Feb": monb = 02;
case "Mar": monb = 03;
case "Apr": monb = 04;
case "May": monb = 05;
case "Jun": monb = 06;
case "Jul": monb = 07;
case "Aug": monb = 08;
case "Sep": monb = 09;
case "Oct": monb = 10;
case "Nov": monb = 11;
case "Dec": monb = 12;
}
slashDate = monb + "/" + da + "/" + yr;
document.getElementById('titleDate').innerHTML = slashDate;


The problem is that the date produced by the SWITCH statement is wrong!?!? Can anyone help explain why the date produced by the IF statements is correct and the date produced by the SWITCH statement is incorrect? Any help would be much appreciated! Thanks


Aucun commentaire:

Enregistrer un commentaire