A useful object in the JavaScript library is the Date object.
We now know the difference between primative and reference types, and we know that JavaScript treats primative types as objects(aka reference types) when using methods.
A date object, however, needs to be declared for us to work with dates.
We declare a date object by simply saying:
let today = new Date();
Setting the variable equal to new Date(); constructs a new date object that the today variable is a reference to.
There may be an instance in which you wish to create a date object that does not represent the current time. To specify a date, we add the date we want within the parenthesis, in the order (Year, Month, Day, Hour, Minute, Seconds, and Milliseconds). we do not have to provide all of these parameters, however. For example, we can provide only the year, month, and day:
let myBirthday = new Date(1997, 7, 29);
We can apply many useful methods to the date object. For most of these, our examples will be in codepen so that you can see the date in real time.
See all the date methods here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
syntax: .getFullYear()
examples:
See the Pen 3.7 Example by LSU DDEM (@lsuddem) on CodePen.
syntax: .getMonth()
examples:
See the Pen 3.7 Example_1 by LSU DDEM (@lsuddem) on CodePen.
Because the month method gives us the month as a number starting at 0, we can easily create an array to convert our month into text. The following example demonstrates this approach.
See the Pen 3.7 Example_2 by LSU DDEM (@lsuddem) on CodePen.
syntax: .getDate()
examples:
See the Pen 3.7 Example_3 by LSU DDEM (@lsuddem) on CodePen.
syntax: .getDay()
examples:
See the Pen 3.7 Example_4 by LSU DDEM (@lsuddem) on CodePen.
syntax: .getHours()
examples:
See the Pen 3.7 Example_5 by LSU DDEM (@lsuddem) on CodePen.
syntax: .getMinutes()
examples:
See the Pen 3.7 Example_6 by LSU DDEM (@lsuddem) on CodePen.
syntax: .getSeconds()
examples:
See the Pen 3.7 Example_6 by LSU DDEM (@lsuddem) on CodePen.
Note: try reloading this pen, the seconds will be different!
syntax: .setDate()
examples:
See the Pen 3.7 Example_7 by LSU DDEM (@lsuddem) on CodePen.
syntax: .setFullYear()
examples:
See the Pen 3.7 Example_7 by LSU DDEM (@lsuddem) on CodePen.
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)
See the Pen Exercise 3.7 by LSU DDEM (@lsuddem) on CodePen.