JavaScript is partly an object-oriented language.
To learn JavaScript, we got to learn the object-oriented parts of JavaScript.
In this article, we’ll look at the Date
object.
Date
The Date
constructor lets us create date objects.
We can create a new Date
instance by passing in nothing, a date string, values for day, month, time, etc., or a timestamp.
For instance, to create the date with the current date, we can write:
new Date();
Also, we can pass in a date string:
new Date('2020 1 1');
and we get:
Wed Jan 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)
or:
new Date('1 1 2020');
and we get:
Wed Jan 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Or:
new Date('1 jan 2020');
and we get:
Wed Jan 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)
The Date
constructor can figure out the date from different strings.
We can also pass in numeric values to the the Date
constructor to represent the:
- year
- month, with 0 representing January to 11 for December
- day — 1 to 31
- hour — 0 to 23
- minutes — 0 to 59
- seconds — 0 to 59
- milliseconds — 0 to 999
For example, we can write:
new Date(2020, 0, 1, 17, 05, 03, 120);
And we get:
Wed Jan 01 2020 17:05:03 GMT-0800 (Pacific Standard Time)
If we pass in a number that’s out of range, it’ll be adjusted to be in range.
For instance, if we have:
new Date(2020, 11, 32, 17, 05, 03, 120);
Then we get:
Fri Jan 01 2021 17:05:03 GMT-0800 (Pacific Standard Time)
We can also pass in a timestamp.
For instance, we can write:
new Date(1557027200000);
And we get:
Sat May 04 2019 20:33:20 GMT-0700 (Pacific Daylight Time)
If we called Date
without new
, then we get a string representing the current date.
It doesn’t matter whether we pass in the parameters.
So if we have:
Date();
We get:
"Mon Aug 03 2020 15:02:32 GMT-0700 (Pacific Daylight Time)"
Date Methods
We can adjust the date with some instance methods.
For instance, we can use getMonth()
, setMonth()
, getHours()
, setHours()
, etc. to set the parts of a date.
To return a string, we call toString
:
const d = new Date(2020, 1, 1);
d.toString();
Then we get:
"Sat Feb 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)"
To set the month, we call setMonth
:
d.setMonth(2)
This returns the new timestamp:
1583049600000
To get a human-readable date, we can call toString
:
d.toString();
and get:
"Sun Mar 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)"
We can get the timestamp of a date with Date.UTC
:
Date.UTC(2029, 0, 1);
And we can pass that into the Date
constructor:
new Date(Date.UTC(2029, 0, 1))
The now
method also returns the current timestamp, so we write:
Date.now();
and we get:
1596492422408
We can do the same with valueOf
or the +
operator:
new Date().valueOf();
+new Date();
and they both return the current timestamp.
Conclusion
Dates can be manipulated with the Date
constructor with JavaScript.
We can convert between timestamps, date objects, and string.