How to format javascript date

Earlier we have gone through the different inbuilt function of java script. You can go over through it Working with dates in javascript.  In this section we will cover the way to achieve different date format in javascript.

How to format javascript date we will look in detail.

There are numerous java script library to achieve different date format. But most of the library are incomplete or bulky or slow. I will cover most simple way to achieve this with inbuilt java script methods.

The below line of code will assign current date and time in object.

var dt = new Date();

Now simply write the above output in browser window with below code.

document.write(“Date : ” + dt );

and the output will be something like below.

Mon Sep 15 2016 23:20:38 GMT+0530 (India Standard Time)

Now as you can see the above output date format, it mostly contain every thing we wanted from date. But in most practical scenario this doesn’t fit in the requirement. Lets go over through some basic date format example with java script.

Format Code
MM/DD/YYYY var dt = new Date();document.write((parseInt(dt.getMonth()) + 1) + “/” + dt.getDate() + “/” + dt.getFullYear());
YYYY.MM.DD var dt = new Date();document.write(dt.getFullYear() + “.” + (parseInt(dt.getMonth()) + 1) + “.” + dt.getDate());
DD/MM/YYYY var dt = new Date();document.write(dt.getDate() + “/” + (parseInt(dt.getMonth()) + 1) + “/” + dt.getFullYear());
DD-MM-YYYY var dt = new Date();document.write(dt.getDate() + “-” + (parseInt(dt.getMonth()) + 1) + “-” + dt.getFullYear());
HH:MM:SS var dt = new Date();document.write((parseInt(dt.getHours())) + “:” + (parseInt(dt.getMinutes())) + “:” + (parseInt(dt.getSeconds())));

The out put is something like below.

 

DateFormat
Date Formatter

You can modify the above code as per your requirement.

Leave a Reply