Replacing month name with number

So far i have changed the date format from "24 Feb 2014" to "Feb-24-2014" using:

    var dateStart = date;
    var arr = dateStart.split(' ');
    console.log(arr[1]+"-"+arr[0]+"-"+arr[2]);

How would I extract the month from arr[1] and replace its equivalent numerical value?

(WHAT i'VE TRIED: I've created an array and an each function to loop through this array and return the month names values (i.e, 2 from Feb, 5 from May)).

ANSWER: The bit that I was looking for specifically in my case was creating the split "arr[1]" as an indexer for the dateArray:

dateArray[arr[1]]

Answers


Use a hash - like that you don't have to iterate over an array.

 var dateHash = {
    Jan : 1,
    Feb: 2,
    Mar: 3,
    Apr: 4,
    May: 5,
    Jun: 6,
    Jul: 7,
    Aug: 8,
    Sep: 9,
    Oct: 10,
    Nov: 11,
    Dec: 12
   };

var newDate = dateHash[arr[1]]+"-"+arr[0]+"-"+arr[2];

Just for fun I did this:

function getMonthFromString(mon){
   return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1
}

Bonus: it also supports full month names :-D Or the new improved version that simply returns -1 - change it to throw the exception if you want (instead of returning -1):

function getMonthFromString(mon){

   var d = Date.parse(mon + "1, 2012");
   if(!isNaN(d)){
      return new Date(d).getMonth() + 1;
   }
   return -1;
 }

Source : HERE


You could keep an object of key/value pairs where the key is the month name and the value is the month number:

var months = {
    January: 1,
    February: 2,
    ...
};

and then:

var monthNumber = months['April'];

or:

Reference Converting month name to month number using JavaScript


use:

var i;
  for (i = 0; i < arr.length; ++i) {
    alert(new Date(Date.parse(arr[i] +" 1, 2012")).getMonth()+1);
}

demo


var month=new Array(12);
        month[0]="Jan";
        month[1]="Feb";
        month[2]="Mar";
        month[3]="Apr";
        month[4]="May";
        month[5]="Jun";
        month[6]="Jul";
        month[7]="Aug";
        month[8]="Sep";
        month[9]="Oct";
        month[10]="Nov";
        month[11]="Dec";

month[mm] === value!!

Need Your Help

Dropdown in PHP

css cross-browser drop-down-menu

I am using PHP 5.2 on SUN OS server. Having problems with the following piece of code that for a drop down:

Appending Item to dropdown list without selecting the item

jquery selected

I have a form wherr I fill in an item name and immediately after I hit submit the item adds to the select dropdownlist and is automatically selected. Is there a way not to have this newly added item