JS Basic - JS string, convert Date format

0 votes
206 views
added Apr 19, 2020 in Javascript by lcjr First Warrant Officer (11,850 points)
//Write a function that converts user keyed date formatted as M/D/YYYY  API format data (YYYYMMDD). 

//The "userDate" parameter and return value are strings. E.g, it should convert user keyed date of "01/16/1996" to "19960116" that fit the API format. 
function formatDate(userDate) {
  userDate = new Date(userDate);
  y = userDate.getFullYear().toString();
  m = (userDate.getMonth() + 1).toString();
  d = userDate.getDate().toString();
  if (m.length == 1) m = '0' + m;
  if (d.length == 1) d = '0' + d;
  return y + m + d;
}

console.log(formatDate("01/16/1996"));

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...