Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

JavaScript Date


The JavaScript date object can be used to get year, month and day. You can display a timer on the webpage by the help of JavaScript date object.

You can use different Date constructors to create date object. It provides methods to get and set day, month, year, hour, minute and seconds.


Constructor

You can use 4 variant of Date constructor to create date object.

  1. Date()
  2. Date(milliseconds)
  3. Date(dateString)
  4. Date(year, month, day, hours, minutes, seconds, milliseconds)

JavaScript Date Methods

The important methods of date object are as follows:

Method Description
getFullYear() returns the year in 4 digit e.g. 2015. It is a new method and suggested than getYear() which is now deprecated.
getMonth() returns the month in 2 digit from 1 to 31.
getDate() returns the date in 1 or 2 digit from 1 to 31.
getDay() returns the day of week in 1 digit from 0 to 6.
getHours() returns all the elements having the given name value.
getMinutes() returns all the elements having the given class name.
getSeconds() returns all the elements having the given class name.
getMilliseconds() returns all the elements having the given tag name.

JavaScript Date Example

Let’s see the simple example to print date object. It prints date and time both.

  1. Current Date and Time: <span id=“txt”></span>
  2. <script>
  3. var today=new Date();
  4. document.getElementById(‘txt’).innerHTML=today;
  5. </script>

Test it Now

Output:

Current Date and Time: Mon Jul 25 2016 16:22:44 GMT+0530 (India Standard Time)

JavaScript Current Time Example

Let’s see the simple example to print current time of system.

  1. Current Time: <span id=“txt”></span>
  2. <script>
  3. var today=new Date();
  4. var h=today.getHours();
  5. var m=today.getMinutes();
  6. var s=today.getSeconds();
  7. document.getElementById(‘txt’).innerHTML=h+”:”+m+”:”+s;
  8. </script>

Test it Now

Output:

Current Time: 16:22:44

JavaScript Digital Clock Example

Let’s see the simple example to display digital clock using JavaScript date object.

There are two ways to set interval in JavaScript: by setTimeout() or setInterval() method.

  1. Current Time: <span id=“txt”></span>
  2. <script>
  3. window.onload=function(){getTime();}
  4. function getTime(){
  5. var today=new Date();
  6. var h=today.getHours();
  7. var m=today.getMinutes();
  8. var s=today.getSeconds();
  9. // add a zero in front of numbers<10
  10. m=checkTime(m);
  11. s=checkTime(s);
  12. document.getElementById(‘txt’).innerHTML=h+”:”+m+”:”+s;
  13. setTimeout(function(){getTime()},1000);
  14. }
  15. //setInterval(“getTime()”,1000);//another way
  16. function checkTime(i){
  17. if (i<10){
  18.   i=“0” + i;
  19.  }
  20. return i;
  21. }
  22. </script>

Test it Now

Output:

Current Time: 16:22:57

Comments

comments