LEARNING JAVASCRIPT - Trang 251

const

m

=

moment

();

// now

m

.

add

(

3

,

'days'

);

// m is now three days in the future

m

.

subtract

(

2

,

'years'

);

// m is now two years minus three days in the past

m

=

moment

();

// reset

m

.

startOf

(

'year'

);

// m is now Jan 1 of this year

m

.

endOf

(

'month'

);

// m is now Jan 31 of this year

Moment.js also allows you to chain methods:

const

m

=

moment

()

.

add

(

10

,

'hours'

)

.

subtract

(

3

,

'days'

)

.

endOf

(

'month'

);

// m is the end of the month you would be in if you
// traveled 10 hours into the future then 3 days back

User-Friendly Relative Dates

Very often, it’s nice to be able to present date information in a relative fashion: “three

days ago” as opposed to a date. Moment.js makes this easy:

moment

().

subtract

(

10

,

'seconds'

).

fromNow

();

// a few seconds ago

moment

().

subtract

(

44

,

'seconds'

).

fromNow

();

// a few seconds ago

moment

().

subtract

(

45

,

'seconds'

).

fromNow

();

// a minute ago

moment

().

subtract

(

5

,

'minutes'

).

fromNOw

();

// 5 minutes ago

moment

().

subtract

(

44

,

'minutes'

).

fromNOw

();

// 44 minutes ago

moment

().

subtract

(

45

,

'minutes'

).

fromNOw

();

// an hour ago

moment

().

subtract

(

5

,

'hours'

).

fromNOw

();

// 4 hours ago

moment

().

subtract

(

21

,

'hours'

).

fromNOw

();

// 21 hours ago

moment

().

subtract

(

22

,

'hours'

).

fromNOw

();

// a day ago

moment

().

subtract

(

344

,

'days'

).

fromNOw

();

// 344 days ago

moment

().

subtract

(

345

,

'days'

).

fromNOw

();

// a year ago

As you can see, Moment.js has chosen some arbitrary (but reasonable) breakpoints

for when to switch to displaying a different unit. It’s a handy way to get user-friendly

relative dates.

Conclusion

If you take away three things from this chapter, they should be the following:

• Internally, dates are represented as the number of milliseconds from the Unix

Epoch (Jan 1, 1970 UTC).

• Be aware of the time zone when you’re constructing dates.
• If you want sophisticated date formatting, consider Moment.js.

User-Friendly Relative Dates | 227