71

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
  • 72,637
  • 105
  • 156
  • 238
user1451890
  • 975
  • 2
  • 12
  • 17

2 Answers2

175

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
  • 143,080
  • 41
  • 260
  • 285
49

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
  • 20,124
  • 10
  • 69
  • 102
  • 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