views:

42

answers:

3

How can we convert a string (2007-01) to date in javascript?

+1  A: 

You could use datejs library to help with the conversions.

Marek Karbarz
+1  A: 
x="2007-01".split("-")
new Date(parseInt(x[0]),parseInt(x[1])-1)
Mon Jan 01 2007 00:00:00 GMT+0000
S.Mark
+2  A: 

You can use either a regular expression or use the String.split function to get the date parts and correctly build a Date object:

// RegExp approach:
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  return new Date(parts[0], parts[1]-1, parts[2] || 1); // months are 0-based
}

parseDate('2007-01');
// Mon Jan 01 2007 00:00:00

// String.split approach:
function parseDate(input, separator) {
  var parts = input.split(separator);
  return new Date(parts[0], parts[1]-1, parts[2] || 1);
}

parseDate('2007-01', '-');
// Mon Jan 01 2007 00:00:00

The above functions can take complete dates (yyyy-mm-dd) or only month dates as you want (yyyy-mm), if the day date part is not present, the first day of the month is assigned.

CMS
upvoted for the months comment :)
medopal
How can we convert the date into Month, Year formateg: January, 2007