Date Formatting in JavaScript with Intl .DateTimeFormat

Date Formatting in JavaScript with Intl .DateTimeFormat

Use Intl.DateTimeFormat in Javascript and set an option for that. it is simple and more usable. Format DateTime in Javascript is a simple thing in Javascript programming that so many programmers left and use library or plugin.

Javascript Format Datetime

Default Javascript Format DateTime

Default Javascript Format DateTime is a long date with time. Here's an example of javascript default DateTime.

<html>
  <head>
   <title>Javascript Format Datetime</title>
  </head>
  <body>
  <h1 id="H_datetime"></h1>

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

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

Output

Fri Sep 18 2020 16:23:40 GMT+0530 (India Standard Time)

 

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

Output

18-9-2020 16:29

Show date with the month name example.

<script type="text/javascript">
    var datetime = document.getElementById('H_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>

Output

September 18, 2020

 

getMonth() method returns month between 0 to 11, but we have to add 1 to match the current month.

<script type="text/javascript">
    var datetime = document.getElementById('H_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>

Output

Friday, 18-9-2020 16:39

Intl.DateTimeFormat

As local time

const date = new Date(2020, 09, 21, 3, 0, 0)

As UTC time

const date = new Date(Date.UTC(2020, 09, 21, 3, 0, 0))

From ISO strings

const date = new Date('2020-09-20T12:00:00Z')

 

 

2021-10-03