76

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>
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
user1451890
  • 1,055
  • 2
  • 13
  • 19

2 Answers2

181

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"
maerics
  • 151,642
  • 46
  • 269
  • 291
50

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('/');
}
Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
  • 1
    Also see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString – Trevor Dixon Jun 02 '21 at 12:11