WDN Logo

home-icon Home / JavaScript / Getting current time using JavaScript

Getting current time using JavaScript

Get current time using JavaScript

Format #5: day date month name year (something like, Wednesday 21st March 2001)

The getDay() method returns a number that specifies the day of the week. Sunday is represented by 0, Monday by 1 and so on. Here again we employ an array. This array would contain the Day names.

<script type="text/javascript">
<!--

var d_names = new Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");

var m_names = new Array("January", "February", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December");

var d = new Date();
var curr_day = d.getDay();
var curr_date = d.getDate();
var sup = "";
if (curr_date == 1 || curr_date == 21 || curr_date ==31)
   {
   sup = "st";
   }
else if (curr_date == 2 || curr_date == 22)
   {
   sup = "nd";
   }
else if (curr_date == 3 || curr_date == 23)
   {
   sup = "rd";
   }
else
   {
   sup = "th";
   }
var curr_month = d.getMonth();
var curr_year = d.getFullYear();

document.write(d_names[curr_day] + " " + curr_date + "<SUP>"
+ sup + "</SUP> " + m_names[curr_month] + " " + curr_year);

//-->
</script>

Sponsored Links

Note: For the sake of clarity, I’ve written the code for the arrays and the write() statement have been written on multiple lines. For usage, you would have to put this on a single line.

The Day name is accessed from the array using the value returned by getDay() as index.

The code above prints: :

Format #6: Hours:Minutes (Finding the time)

Hours and minutes are obtained using getHours() and getMinutes() methods of the date object. The value returned by gethours() varies from 0 to 23.

<script type="text/javascript">
<!--

var d = new Date();

var curr_hour = d.getHours();
var curr_min = d.getMinutes();

document.write(curr_hour + " : " + curr_min);

//-->
</script>

Print:

There are two problem here. Firstly, if the hour or minutes is in single digits, JavaScript does not add any leading zeroes. Hence, 05:03 (AM) is printed as 5:3. Secondly, 12:00 AM becomes 0:00 (!). Let’s see how to format time correctly.

Sponsored Links

Search

Your comments
Star icon IMPORTANT Have a question / problem? Click here to ask an expert.

Caps Lock jokes and funny images

Sponsored Links

Tips

How do I view a deleted web page?
Is there a way to view a deleted web page - one that is no longer available? Yes there is and the solution is quite simple. [more...]

Fact

Starting out in 1990 as unix shell search scripts and four lists (of actors, actresses, dead actors/actresses and directors), IMDb was made into an independent web site developed and maintained by Col Needham and his friends. [more...]

Share on Whats app Share on Facebook Share on Twitter Share on Google plus