Javascript change date into format of (dd/mm/yyyy)

Javascript

Javascript Problem Overview


How can I convert the following date format below (Mon Nov 19 13:29:40 2012)

into:

dd/mm/yyyy

<html>
    <head>
    <script type="text/javascript">
      function test(){
         var d = Date()
         alert(d)
      }
    </script>
    </head>

<body>
    <input onclick="test()" type="button" value="test" name="test">
</body>
</html>

Javascript Solutions


Solution 1 - Javascript

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

function convertDate(inputFormat) {
  function pad(s) { return (s < 10) ? '0' + s : s; }
  var d = new Date(inputFormat)
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')
}

console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"

Solution 2 - Javascript

This will ensure you get a two-digit day and month.

function formattedDate(d = new Date) {
  let month = String(d.getMonth() + 1);
  let day = String(d.getDate());
  const year = String(d.getFullYear());

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

  return `${day}/${month}/${year}`;
}

Or terser:

function formattedDate(d = new Date) {
  return [d.getDate(), d.getMonth()+1, d.getFullYear()]
      .map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1451890View Question on Stackoverflow
Solution 1 - JavascriptmaericsView Answer on Stackoverflow
Solution 2 - JavascriptTrevor DixonView Answer on Stackoverflow