LEARNING JAVASCRIPT - Trang 250

d

.

getHours

()

// 17

d

.

getMinutes

()

// 0

d

.

getSeconds

()

// 0

d

.

getMilliseconds

()

// 0

// there are allso UTC equivalents to the above:

d

.

getUTCFullYear

()

// 1815

d

.

getUTCMonth

()

// 9 - October

d

.

getUTCDate

()

// 10

// ...etc.

If you’re using Moment.js, you’ll find little need to work with individual components,

but it’s good to know that they’re there.

Comparing Dates

For simple date comparisons—does date A come after date B or vice versa?—you can

use JavaScript’s built-in comparison operators. Remember that

Date

instances store

the date as a number, so the comparison operators simply work on the numbers:

const

d1

=

new

Date

(

1996

,

2

,

1

);

const

d2

=

new

Date

(

2009

,

4

,

27

);

d1

>

d2

// false

d1

<

d2

// true

Date Arithmetic

Because dates are just numbers, you can subtract dates to get the number of millisec‐

onds between them:

const

msDiff

=

d2

-

d1

;

// 417740400000 ms

const

daysDiff

=

msDiff

/

1000

/

60

/

60

/

24

;

// 4834.96 days

This property also makes it easy to sort dates using

Array.prototype.sort

:

const

dates

=

[];

// create some random dates

const

min

=

new

Date

(

2017

,

0

,

1

).

valueOf

();

const

delta

=

new

Date

(

2020

,

0

,

1

).

valueOf

()

-

min

;

for

(

let

i

=

0

;

i

<

10

;

i

++

)

dates

.

push

(

new

Date

(

min

+

delta

*

Math

.

random

()));

// dates are random and (probably) jumbled
// we can sort them (descending):

dates

.

sort

((

a

,

b

)

=>

b

-

a

);

// or ascending:

dates

.

sort

((

a

,

b

)

=>

a

-

b

);

Moment.js brings many powerful methods for doing common date arithmetic, allow‐

ing you to add or subtract arbitrary units of time:

226 | Chapter 15: Date and Time