Javascript Format Datetime

by Didin J. on Dec 24, 2016 Javascript Format Datetime

Javascript Format Datetime is simple thing in Javascript programming that so many programmers left and use library or plugin.

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>
That example will display full javascript datetime on the screen.

Full Javascript Datetime

 

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 a result.

24-12-2016 6:11

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

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

Example to show full date with day 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 month 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's was very easy using pure javascript for format datetime.

Thanks.

The following resources might be useful for you:

Loading…