Format Date in Javascript

Recently I have come across a use case where the requirement was to display dates in a particular format . The project is developed in Vanilla Javascript. After doing some analysis I found that there is no inbuilt function in javascript to perform this job unless you want to include a libraries like "moment.js". If you dont want to use 2rd party libarary then you can write your own function like below to achieve this.

function formatDates(input) {
  var date = new Date(input);
  var day = date.getDate();
  //getMonth function returns the month starting from 0
  var month = date.getMonth() + 1; 
  var year = date.getFullYear();
  return [day, month, year].join("-");
}

Here first of all I am taking a date string and converting it to date object.Then after getting the individual parts of dates like day, month, year and in the end concatenate it in the desired format. Please note "getMonth" function return the month starting from 0 hence adding 1 into it.

var newDate = formatDates("01/31/2020");
newDate :- '31-1-2020'

This is do the work but there is 1 problem with this function. What if you want your result like this

31-01-2020

In this case you need to write your function like this

function formatDatesWithLeadingZero(input) {
  var date = new Date(input);
  var day = ("0" + date.getDate()).slice(-2);
  var month = ("0" + (date.getMonth() + 1)).slice(-2);
  var year = date.getFullYear();
  return [day, month, year].join("-");
}

Let me walk through the code. As we want leading zero in date and month, we are appending a "0" before the values. Which will give us result either "01" or "031" based on date value, then we are using slice function with negative indexes to get the last 2 characters out of the string. It will return "01" or "31".

Here is the code sandbox link to play with. CodeSandBox

References:-

developer.mozilla.org/en-US/docs/Web/JavaSc.. stackoverflow.com/questions/23593052/format..