Tuesday, April 12, 2016

Convert a numeric month to a string month name

function convertMonthToWords(intMonth) {
  var strMonth = "";

  if (intMonth == undefined || intMonth == isNaN || Number(intMonth) < 1 || Number(intMonth) > 12) {
    strMonth = "Invalid Month";
  }
  else {
    var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    strMonth = monthNames[Number(intMonth - 1)];  // -1 because javascript month starts with 0 for January
  }
  return strMonth

}

Use it like this:
var strMonth = convertMonthToWords(2);    // strMonth will be March

No comments:

Post a Comment