In the previous lesson, you had a go at manipulating text by taking advantage of the powerful properties and methods of the String object.
Here we continue to explore the power of JavaScript objects: we will be looking into the magical virtues of the Date object.
Here’s what you will do in this lesson:
- create a Date object;
- set dates;
- compare dates.
The Date object
In lesson 8 you learned how to retrieve the current date and display it on the web page in user-friendly format. This could be done dynamically thanks to the JavaScript goodness offered by the Date object.
The Date object exposes plenty of methods to manipulate dates and times, some of which we’re going to examine here.
I recommend you try out all the demos below by inserting the code snippets between enclosing <script> tags in an HTML page (for such short demos we can get away with not using an external JavaScript file ). Also, feel free to experiment with each demo as much as possible before moving on to the next example.
Create a Date object
You create a date object by using one of the following ways:
//First way: //the var today is initialized with a Date object //containing the current date and time //on the basis of the user's computer //use toLocaleDateString() to adjust the date //to the local time zone and format it automatically var today = new Date().toLocaleDateString(); //Second way: //you pass a millisecond argument that starts at 1970/01/01: //new Date(milliseconds) var date = new Date(1000).toLocaleDateString(); //On my system this outputs: 01 January 1970 //Third way: //You pass a string as argument: //new Date(dateString) var date = new Date("10 November, 2011").toLocaleDateString(); //On my system this outputs: 10 November 2011 Fourth way: //new Date(year, month, day, hours, minutes, seconds, milliseconds) //only year and month are required, //the others are optional arguments and //where not present 0 is passed by default //Below you pass the year in a 4-digit format, and the month in number form: //months are represented by numbers from 0 (January) to 11 (December) var date = new Date(2011, 10).toLocaleDateString(); //On my system this outputs: 01 November 2011
After a Date object is created, you can use its methods to get and set dates and times.
Use getDate() to retrieve a date
//Create a Date object containing the current date and time var myDate = new Date(); //use getDate() to extract the day of the month document.write(myDate.getDate()); //At the time of writing, this prints 11 //days of the month range from 1 to 31
Use getTime() to retrieve a time
//Create a Date object containing the current date and time var myTime = new Date(); //use getTime() to extract the time document.write(myTime.getTime()); //At the time of writing, this prints 1321021815555 //This is the millisecond representation of the current //date object: the number of milliseconds between //1/1/1970 (GMT) and the current Date object
Get Date object components
Once you have a Date object, one interesting thing you can do with it is to get its various components. JavaScript offers some interesting methods to do just that.
Use getFullYear() to extract the year component
//Create a Date object containing the current date and time var myDate = new Date(); //extract the year component and print it on the page document.write(myDate.getFullYear()); //At the time of writing, this prints 2011
Use getMonth() to extract the month component
//Create a Date object containing the current date and time var myDate = new Date(); //extract the month component and print it on the page document.write(myDate.getMonth()); //At the time of writing, this prints 10 //which represents the month of November - months are represented //with numbers starting at 0 (January) and ending with 11 (December)
Use getDay() to extract the day component
//Create a Date object containing the current date and time var myDate = new Date(); //extract the day component and print it on the page document.write(myDate.getDay()); //At the time of writing, this prints 5 //which represents Friday - days are represented //with numbers starting at 0 (Sunday) and ending with 6 (Saturday)
Use getHours() and getMinutes() to extract time components
//Create a Date object containing the current date and time var myDate = new Date(); //extract the hours component var hours = myDate.getHours(); //extract the minutes component var minutes = myDate.getMinutes(); //format and display the result on the page: //check the minutes value is greater than 1 digit //by being less than 10 if (minutes < 10) { //If it's just a one digit number, then add a 0 in front minutes = "0" + minutes; } var timeString = hours + " : " + minutes; document.write(timeString); //Based on my computer clock, this prints: //14 : 44
Set dates
You can also set dates and times as easily as calling the appropriate methods. Here are a few examples.
Use setFullYear() to set a specific date
In this demo, you will set a specific date and then retrieve its day component for display
//Create a Date object containing the current date and time var myDate = new Date(); //set the Date object to a specific date: 31 October, 2011 var mySetDate = myDate.setFullYear(2011, 9, 31); //Now retrieve the newly set date var mySetDay = myDate.getDay(mySetDate); //mySetDay will contain a number between 0 - 6 (Sunday - Saturday). //Use mySetDay as test case for a switch statement //to assign the corresponding week day to the number value switch (mySetDay) { case 0: mySetDay = "Sunday"; break; case 1: mySetDay = "Monday"; break; case 2: mySetDay = "Tuesday"; break; case 3: mySetDay = "Wednesday"; break; case 4: mySetDay = "Thursday"; break; case 5: mySetDay = "Friday"; break; case 6: mySetDay = "Saturday"; break; } //display the result on the page document.write("The 31st October 2011 is a " + mySetDay); //If you check the date on a calendar, you'll find that //the 31st Oct 2011 is indeed a Monday
Compare 2 dates
In this demo you will compare 2 Date objects.
//Create a Date object var myDate = new Date(); //set the Date object to a specific date: 31 October, 2011 var mySetDate = myDate.setFullYear(2011, 9, 31); //Create a second Date object var now = new Date(); //Make the comparison: if the set date is bigger than today's date if (mySetDate > now) { //the set date is in the future document.write("The 31st October is in the future"); } //if the set date is smaller than today's date, it's in the past else { document.write("The 31st October is in the past"); }
Summary
In this lesson you looked into some of the methods of the Date object and had the chance to experiment with them.
In the next lesson you will be exploring JavaScript mathematical wizardry: get ready for the Math object.