Javascript Format Datetime

274

- Advertisement -

Default Javascript Format Datetime is a long date with time. Here’s an example of javascript default datetime.

<html>
  <head>
   <title>Javascript Datetime</title>
  </head>
  <body>

  <h1 id="datetime"></h1>

  <script type="text/javascript">
    var datetime = document.getElementById('datetime');
    var defaultdatetime = new Date();

    datetime.innerHTML = defaultdatetime;
  </script>
  </body>
</html>

We can display a datetime in more human readable using this method.

<script type="text/javascript">
  var datetime = document.getElementById('datetime');
  var d = new Date();
  var formatted = d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes();

  datetime.innerHTML = formatted;
</script>

Here’s the result.

24-12-2016 6:11

This is not really pretty code, but easier to implement and compatible with all browsers without adding another javascript library.

We have to remember that getMonth() method returns months between 0 to 11, so we have to add 1 to match current month.

Here’s an example to show full date with the day’s name.

<script type="text/javascript">
  var datetime = document.getElementById('datetime');
  var dayname = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  var d = new Date();
  var formatted = dayname[d.getDay()]+", "+d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes();

  datetime.innerHTML = formatted;
</script>

Result:

Saturday, 24-12-2016 6:11

Example to show date with the month’s name.

<script type="text/javascript">
  var datetime = document.getElementById('datetime');
  var monthname = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  var d = new Date();
  var formatted = monthname[d.getMonth()]+" "+d.getDate()+", "+d.getFullYear();

  datetime.innerHTML = formatted;
</script>

Result:

December 24, 2016

That was very easy using pure javascript to format datetime.

Thanks.

Leave A Reply

Your email address will not be published.