Date Properties are fairly normal with just the constructor and prototype, neither of which are commonly used.
Common Date Methods
The date object can either get or set times and can compare times.
I am not going to show the examples here, but you should know that all of the date methods that get time return integers. If it was monday getDay() would return 1 instead of Monday (Sunday returns 0).
- getFullYear() – gets the year (Ex. 2012)
- getMonth() – gets the month, where January is 0 and December is 11
- getDate() – gets the day of the month
- getDay() – gets the day of the week, where Sunday is 0 and Saturday is 6
- getHours() – gets the hour
- getMinutes() – gets the minutes
- getSeconds() – gets the seconds
- getMilliseconds() – gets the milliseconds, remember that there are 1000 milliseconds in a second
While I would say the best way to set a time is when you create it, I understand that there are a few reasons to change a time after it has been set.
- setFullYear() – sets the year (Ex. 2012)
- setMonth() – sets the month, where January is 0 and December is 11
- setDate() – sets the day of the month
- setDay() – sets the day of the week, where Sunday is 0 and Saturday is 6
- setHours() – sets the hour
- setMinutes() – sets the minutes
- setSeconds() – sets the seconds
- setMilliseconds() – sets the milliseconds, remember that there are 1000 milliseconds in a second
Setting and getting times are extremely useful, but what if you want to compare them?
You have to remember that the nowTime above is a date object. It would not work to say is now time <= some number.
Finally, we have one last important topic to cover with date objects.
- toString() - converts a date object to a string
The date method toString() is useful when you would like to display only parts of a time in a string. This allows you to join the strings together to show exactly what parts of the time you would like to display. Let's go through an example for a better explanation.
Now you see that, if you don't use the toString(), the year and month are added. However, if we use the toString() methods when we add them we get 20123, which is the year and the month joined not added. I put the day in the example above so you can see that they are not added if a string separates them. So, if you want to use the date objects as strings, use the toString() just to be safe.
0 thoughts on “Date Object”
Finally know how to do this!