LEARNING JAVASCRIPT - Trang 245

new

Date

(

2015

,

0

);

// 12:00 A.M., Jan 1, 2015

new

Date

(

2015

,

1

);

// 12:00 A.M., Feb 1, 2015

new

Date

(

2015

,

1

,

14

);

// 12:00 A.M., Feb 14, 2015

new

Date

(

2015

,

1

,

14

,

13

);

// 3:00 P.M., Feb 14, 2015

new

Date

(

2015

,

1

,

14

,

13

,

30

);

// 3:30 P.M., Feb 14, 2015

new

Date

(

2015

,

1

,

14

,

13

,

30

,

5

);

// 3:30:05 P.M., Feb 14, 2015

new

Date

(

2015

,

1

,

14

,

13

,

30

,

5

,

500

);

// 3:30:05.5 P.M., Feb 14, 2015

// creates dates from Unix Epoch timestamps

new

Date

(

0

);

// 12:00 A.M., Jan 1, 1970 UTC

new

Date

(

1000

);

// 12:00:01 A.M., Jan 1, 1970 UTC

new

Date

(

1463443200000

);

// 5:00 P.M., May 16, 2016 UTC

// use negative dates to get dates prior to the Unix Epoch

new

Date

(

-

365

*

24

*

60

*

60

*

1000

);

// 12:00 A.M., Jan 1, 1969 UTC

// parsing date strings (defaults to local time)

new

Date

(

'June 14, 1903'

);

// 12:00 A.M., Jun 14, 1903 local time

new

Date

(

'June 14, 1903 GMT-0000'

);

// 12:00 A.M., Jun 14, 1903 UTC

If you’re trying these examples out, one thing you’ll notice is that the results you get

are always in local time. Unless you are on UTC (hello, Timbuktu, Madrid, and

Greenwich!), the results listed in UTC will be different than shown in this example.

This brings us to one of the main frustrations of the JavaScript

Date

object: there’s no

way to specify what time zone it should be in. It will always store objects internally as

UTC, and format them according to local time (which is defined by your operating

system). Given JavaScript’s origin as a browser-based scripting language, this has tra‐

ditionally been the “right thing to do.” If you’re working with dates, you probably

want to display dates in the user’s time zone. However, with the global nature of the

Internet—and with Node bringing JavaScript to the server—more robust handling of

time zones would be useful.

Moment.js

While this book is about the JavaScript language itself—not libraries—date manipula‐

tion is such an important and common problem that I have decided to introduce a

prominent and robust date library, Moment.js.
Moment.js comes in two flavors: with or without time zone support. Because the time

zone version is significantly larger (it has information about all the world’s time

zones), you have the option of using Moment.js without time zone support. For sim‐

plicity, the following instructions all reference the time zone–enabled version. If you

want to use the smaller version, visit

http://momentjs.com

for information about your

options.
If you’re doing a web-based project, you can reference Moment.js from a CDN, such

as cdnjs:

Moment.js | 221

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.