Let’s see a few points about when to use a date object, and why use this object vs. a date library?
The simplest and quickest way to get date in Javascript -
1
|
console.log(Date.now()); // 1549025852124
|
Date.now()
does not create an object, and is really fast. But, it is also useless if you want to do anything with the date.
Use date objects in numerous ways to format dates, set dates, consider time zones, and for date manipulations.
Output formatted date -
1
2
3
4
|
console.log(new Date()); // 2019-02-01T12:48:45.430Z
const dt = new Date();
console.log(dt.toLocaleString()); // 2/17/2019, 6:19:56 PM
|
Also, create an object with a particular date.
1
2
3
4
5
6
|
const dt = new Date("2019-02-01");
console.log(dt);
//2019-02-01T00:00:00.000Z
console.log(dt.getDate() + "-" + (dt.getMonth() + 1) + "-" + dt.getFullYear());
// 1-2-2019
|
Or, parse a given date -
1
|
console.log(Date.parse("2019-02-01")); // 1548979200000
|
If you have to do date manipulations -
1
2
3
4
5
6
7
|
const yesterday = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() - 1);
// notice timezone
console.log("yesterday: ", yesterday); // 2019-01-30T18:30:00.000Z
const lastMonth = new Date("2019-02-01T05:30:00z");
lastMonth.setMonth(-1);
console.log("lastMonth: ", lastMonth); // 2018-12-01T05:30:00.000Z
|
The date manipulations through the standard date
object works fine. But you are better off using a library if you are doing complex operations involving time zone manipulations, a lot of operations with date or time math, or in those date manipulations where you start valuing readability more and more!
Moment.js and Luxon are two popular libraries to do anything and everything with dates.
For e.g., consider the below example code from the Luxon library.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
var keepOffset = DateTime.fromISO("2017-05-15T09:10:23-09:00", {
setZone: true
});
keepOffset.zoneName; //=> 'UTC-9'
keepOffset.toString(); //=> '2017-05-15T09:10:23.000-09:00'
var keepZone = DateTime.fromFormat(
"2017-05-15T09:10:23 Europe/Paris",
"yyyy-MM-dd'T'HH:mm:ss z",
{
setZone: true
}
);
keepZone.zoneName; //=> 'Europe/Paris'
keepZone.toString(); //=> '2017-05-15T09:10:23.000+02:00'
|
Or, manipulations involving day light saving times.
1
2
3
4
|
let start = DateTime.local(2017, 3, 11, 10);
start.hour; //=> 10, just for comparison
start.plus({ days: 1 }).hour; //=> 10, stayed the same
start.plus({ hours: 24 }).hour; //=> 11, DST pushed forward an hour
|
Also: know more about validating dates in Javascript