Getting current time using JavaScript

Getting current time using JavaScript cover image
  1. Home
  2. JavaScript
  3. Getting 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.

JavaScript