facebook-squared twitter-squared rss-squared gplus-squared



May 2014



Current Date in Javascript

Written by on 9 May 2014

Current Date via Javascript

Current Date can be displayed by using javascript object Date(). Objects in javascript behave similarly as that of real objects, if we compare it with the laptop: which is an object with properties. Each laptop has color, wight, made, material, size etc. Same goes for javascript objects what has properties which define their characteristics


An object is a collection of properties, and a property is an association between a name and a value. A property’s value can be a function, in which case the property is known as a method.

Mozilla Developer Network

In JavaScript we’ve several object at its core like Math, Array, String, Date. We can create one for our self by use Object. In this post we are going to look into our Date Object.

We have seen a lot on the footer of websites how the day,month and year are shown along with copyright symbol.

current date in shoptalkshow footer current date in  smashing magazine footer current date in  mozilla developer networks footer

How it works

In case of php as back end approach one simple line will do the trick like

<?php echo date('y'); ?>

But in case of JavaScript first we have to create an object and assign it to current date like

var now = new Date();

Now with the help of newly created object we can access all the methods of Date objects. Here is a list of some of the available methods

now.getMonth() will return 4, because month are zero indexed so 0 holds true for January and there is no denial that 11 is for December. So in order to display correct we append 1 at the end as:

now.getMonth() + 1;  // returns 5

JavaScript aren’t sophisticated enough to display the name of the month as a string. For this purpose we are going to use array, which holds name of months. We can access the appropriate array item by arguing proper index.

var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];

var month = now.getMonth()+1;

month = monthNames[month];


We are done with months let’s move on to current day and year which is straight forward

now.getDate(); // return 9

now.getYear(); // return 2014

We can enhance the display of date by adding leading zero “0” for dates that are less than 10

(now.getDate()<10 ? '0' : '') + now.getDate(); // return 09


All the coding at one place


function getTime(){

var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];

var now = new Date();

var month = now.getMonth()+1;

month = monthNames[d.getMonth()];

var day = now.getDate();

var output = month + " " + (day<10 ? '0' : '') + day + " " + d.getFullYear();





Leave a Reply

%d bloggers like this: