Javascript TUTORIAL


Javascript Date Objects


The Javascript Date object can be used to access and manipulate the local date and time.

Let us take a look at the following line. It will define a Date object called Datex.


var Datex=new Date()


Initially, the above Datex object will hold the current date and time. We can later on manipulate the date and time using the methods available with the Date object. We can see it in the following example which will do nothing but print the current date and time.

<html>
<body>
<script type="text/javascript">

/*
************************************************************
Example - Javascript Date Object
************************************************************
*/

var Datex=new Date();
document.write(Datex);

</script>
</body>
</html>



You can try the example at the link below which will open in a new window

Example - Javascript Print Current Date

Methods on Date Object


There are a number of Methods available in the Date Object. For example take a look at the following code below which will set the date to 7 days or 1 week from the current date and time.



var Datex=new Date();
Datex.setDate(Datex.getDate()+7);



The following example will set the date to Dec 10, 2008 using the setFullYear method.

There are a number of Methods available in the Date Object. For example take a look at the following code below which will set the date to 7 days or 1 week from the current date and time.



var Datex=new Date();
Datex.setFullYear(2008,12,10);



We will now take a look at an example that will print "Today is Holiday" if Today's day is either Sat or Sunday and Will print "Today is Work day" otherwise.

<html>
<body>
<script type="text/javascript">

/*
************************************************************
Example - Javascript Date Object
************************************************************
*/

var Datex=new Date();

if (  (Datex.getDay() == 0) ||  (Datex.getDay() == 6) )
  {
    
    document.write("Today it is Holiday");
   }

else 
   {

    document.write("Today it Workday");

    }	

</script>
</body>
</html>



To test this program, set your system clock on your to Saturday or Sunday once and some other day at other time. Note that Datex.getDay() will return 0 for Sunday 1 for Monday and so on.

You can try this example online here

Example - Find if today is Holiday