1

Write a function that converts user entered date formatted as M/D/YYYY to a format required by an API (YYYYMMDD). The parameter "userDate" and the return value are strings. For example, it should convert user entered date "12/31/2014" to "20141231" suitable for the API. i tried:

function formatDate(userDate) {
  // format from M/D/YYYY to YYYYMMDD
  a = new Date(userDate);
  y = a.getFullYear();
  m = a.getMonth();
  d = a.getDate();
  return y.toString() + m.toString() + d.toString();
}

console.log(formatDate("12/31/2014"));

where is the problem??

Abde Abde
  • 23
  • 1
  • 6

3 Answers3

3

String#split() the date on / and then concat the generated date, month and year.

function AddLeadingZero(num) {
  return (num < 10 ? '0' : '') + num;
}

function formatDate(userDate) {
  var [month, day, year] = userDate.split('/');
  return year + AddLeadingZero(month) + AddLeadingZero(day); 
}

console.log(formatDate("12/31/2014"));
console.log(formatDate("10/1/2014"));
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
3

The issue is that getMonth() returns a month index from 0 to 11, so December appears as 11 and not 12.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0
var convertDate = function(usDate) {
  var dateParts = usDate.split(/(\d{1,2})\/(\d{1,2})\/(\d{4})/);
  return dateParts[3] + dateParts[1] +  dateParts[2];
}

var inDate = "12/31/2014";
var outDate = convertDate(inDate);

alert(outDate);
pravin dabhi
  • 302
  • 1
  • 11