LEARNING JAVASCRIPT - Trang 246

<

script

src

=

"//cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.4.0/

moment-timezone.min.js"

></

script

>

If you’re working with Node, you can install Moment.js with

npm install --save

moment-timezone

and then reference it from your script with

require

:

const

moment

=

require

(

'moment-timezone'

);

Moment.js is large and robust, and chances are, if you need to manipulate dates, it

has exactly the functionality you need. Consult its

excellent documentation

for more

information.

A Practical Approach to Dates in JavaScript

Now that we have the basics out of the way, and you have Moment.js available, we’re

going to take a slightly different approach to covering this information. An exhaustive

coverage of the methods available on the

Date

object would be dry and not very use‐

ful to most people. Furthermore, if you need that reference,

MDN’s coverage of the

Date

object

is exhaustive and well-written.

Instead, this book will take a more cookbook-based approach and cover the common

date processing needs that people have, and use

Date

and Moment.js where appropri‐

ate.

Constructing Dates

We’ve already covered the construction options available to you with JavaScript’s

Date

object, which are, for the most part, adequate. Whenever you construct a date

without an explicit time zone, you have to think about what time zone is being used,

which is going to be dependent on where the date is being constructed. This has trip‐

ped up many a beginner in the past: they use the same date code on a server in

Arlington, Virginia, as they use in a user’s browser connecting from Los Angeles, Cal‐

ifornia, and they are surprised when the dates are off by three hours.

Constructing Dates on the Server

If you’re constructing dates on the server, I recommend always either using UTC or

explicitly specifying the time zone. With today’s cloud-based approach to application

development, the same code base could be running on servers all over the world. If

you’re constructing local dates, you’re asking for trouble. If you are able to use UTC

dates, you can construct them with the

Date

object’s

UTC

method:

const

d

=

new

Date

(

Date

.

UTC

(

2016

,

4

,

27

));

// May 27, 2016 UTC

222 | Chapter 15: Date and Time

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.