How to format Dates with JavaScript
EasyProgramming.net tutorial on how to format dates in JavaScript!
by Nazmus Nasir
HTML
<!-- Easy JavaScript - Formatting Dates #53 -->
<p>
Welcome to the 53rd Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. Let's format our dates!
</p>
<p>
There are a lot of useful methods for the Date object, and you can find them all listed neatly on <a href="https://www.w3schools.com/jsref/jsref_obj_date.asp" target="_blank">W3Schools</a>, but in this tutorial, we're going to focus on just a few methods:
</p>
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Method</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>getDate()/getUTCDate()</td>
<td>Returns the day of the month (from 1-31)</td>
</tr>
<tr>
<td>getDay()/getUTCDay()</td>
<td>Returns the day of the week (from 0-6)</td>
</tr>
<tr>
<td>getMonth()/getUTCMonth()</td>
<td>Returns the month (from 0-11)</td>
</tr>
<tr>
<td>getFullYear()/getUTCFullYear()</td>
<td>Returns the year</td>
</tr>
<tr>
<td>getHours()/getUTCHours()</td>
<td>Returns the hour (from 0-23)</td>
</tr>
<tr>
<td>getMinutes()/getUTCMinutes()</td>
<td>Returns the minutes (from 0-59)</td>
</tr>
<tr>
<td>getSeconds()/getUTCSeconds()</td>
<td>extract part of a string, first parameter is the start position, and second is the length</td>
</tr>
</tbody>
</table>
CSS
table td{
/* border: #000 solid 1px; */
border-bottom: 1px solid #000;
padding: 5px;
}
JavaScript
var d = new Date(2018, 1, 1, 12, 1, 1, 1);
console.log(d);
console.log(d.getDate());
console.log(d.getDay());
console.log(d.getMonth());
var mon = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
console.log(mon[d.getMonth()] + " " + formatDate(d.getDate()) + ", " + d.getFullYear() + " " + formatDate(d.getHours()) + ":" + formatDate(d.getMinutes()) + ":" + formatDate(d.getSeconds()));
function formatDate(n){
var f = (n < 10) ? "0" + n : n;
return f;
}