0

Is there a better way to write this code? I'm taking a "date" parameter (which is a string in this case) thats formatted in one of two ways mm/dd/yy' or m/d/yy and I need to reformat it to look like this yyyymmdd

functionName = function(date){

  var month = "", day = "", year = "";

  if(!date.length) return;
  else {        
    date.slice(0, 2) < 10 ? month = '0' + date.slice(0, 2) : month = date.slice(0, 2);
    date.slice(3, 5) < 10 ? day = '0' + date.slice(3, 5) : day = date.slice(3, 5);
    year = "20" + date.slice(6, 8); 
  }
  return year + month + day;
}

Also how should I check to see if the date was in the 1900's and format it accordingly?

web-dev
  • 133
  • 2
  • 11
  • 2
    It is impossible to know the difference between 1920 and 2020 with those formats, both will be '/20'. If possible, better to change the format of the "date" that you are receiving instead of trying to rearrange. – Ariel Jul 09 '21 at 19:19
  • Please check this https://stackoverflow.com/questions/5619202/converting-a-string-to-a-date-in-javascript – SRK45 Jul 09 '21 at 19:35

1 Answers1

0

There is no way to make a full year from a two digit year, it's missing information.

However you could simplify your function using .split() and .padStart()

function FormatDate (date) {
  if (date) {
    date = date.split('/'); //date[0] = month, date[1] = day, date[2] = year
    return date[2] + date[0].padStart(2, '0') + date[1].padStart(2, '0');
  }
}

console.log(FormatDate('07/09/20')); //outputs 200709
PoorlyWrittenCode
  • 1,003
  • 1
  • 7
  • 10