Reputation: 8095
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]]
Upvotes: 1
Views: 10173
Reputation: 181
To transform month into number:
var dateString = "24 Feb 2014";
var date = new Date(dateString)
var result = date.getMonth() + 1 + "-" + date.getDate() + "-" + date.getFullYear()
console.log(result)
To transform number into month:
var dateString = "24-2014";
var monthNumber = 2;
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var result = months[monthNumber - 1] + "-" + dateString
console.log(result)
Upvotes: 0
Reputation: 82231
use:
var i;
for (i = 0; i < arr.length; ++i) {
alert(new Date(Date.parse(arr[i] +" 1, 2012")).getMonth()+1);
}
Upvotes: 1
Reputation: 6764
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];
Upvotes: 6
Reputation: 20001
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
Upvotes: 1
Reputation: 695
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!!
Upvotes: -3
Reputation: 9269
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
Upvotes: 0