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

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>

Answers:

Answer

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"

Answer

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('/');
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.