How to format Dates with JavaScript

Published on: June 24, 2017

Welcome to the 53rd Easy JavaScript tutorial, part of EasyProgramming.net. This marks the 52nd straight week, a full year of JavaScript tutorials! Thank you so much for sticking around and for supporting us!

Let's continue where we left off and format our dates so that things look pretty!

In this tutorial we're going to learn how to format a date and make it look pretty. In this tutorial, we use the following formatDate() function to format our dates:

    function formatDate(n){
		var f = (n < 10) ? "0" + n : n;
                return f;
    }

What the above function does is pretty much get a value (n), and does a simple if statement using the ternary operator: if the number is less than 10, add the character "0" in front, otherwise, just return the number. This means that if the minutes of the clock, 2, is sent back, it'll display 02, instead of just 2, which looks a lot better, don't you think? Watch the tutorial below and check out the JS Fiddle for more info. 

To fork the fiddle and follow along: https://jsfiddle.net/easyjs/f5essu53/

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!

Resources:

Comments: