Wednesday, 16 November 2011

get year and month out of a string using javascript

Create an array to store months names.


arrMonths= new Array()
arrMonths[0]='January'
arrMonths[1]='February'
arrMonths[2]='March'
arrMonths[3]='April'
arrMonths[4]='May'
arrMonths[5]='June'
arrMonths[6]='July'
arrMonths[7]='August'
arrMonths[8]='September'
arrMonths[9]='October'
arrMonths[10]='November'
arrMonths[11]='December'
strDate = '2011-04-23'


parseDate = Date.parse( strDate)


objDate = new Date( parseDate)


Now,begin extraction of month,day and year


month = objDate.getMonth( ); // will give you month in integer indexed from '0' :  3
alert( arrMonths[ month] );


year = objDate.getFullYear(); // will give you year: 2011


NOTE:If you're getting '111' as year, then you must be using obsolete getYear() method. Instead use getFullYear().

No comments:

Post a Comment