Thursday, December 21, 2017

[JavaScript][Exercise] converts Date format

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.

Reference answer 1:

function formatDate(userDate) {
  var temp = userDate.split("/");
  if (temp[0].length < 2) temp[0] = '0' + temp[0];
  if (temp[1].length < 2) temp[1] = '0' + temp[1];
  return temp[2]+temp[0]+temp[1];
}

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

Reference answer 2:

function formatDate(userDate) {
    var d = new Date(userDate),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join("");
}

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

Reference

https://stackoverflow.com/questions/23593052/format-javascript-date-to-yyyy-mm-dd

No comments :

Post a Comment