LEARNING JAVASCRIPT - Trang 249

d

.

toLocaleTimeString

()

// "4:00:00 PM"

d

.

toTimeString

()

// "17:00:00 GMT-0700 (Pacific Daylight Time)"

d

.

toUTCString

()

// "Sat, 10 May 1930, 00:00:00 GMT"

moment

(

d

).

format

(

"YYYY-MM-DD"

);

// "1930-05-09"

moment

(

d

).

format

(

"YYYY-MM-DD HH:mm"

);

// "1930-05-09 17:00

moment

(

d

).

format

(

"YYYY-MM-DD HH:mm Z"

);

// "1930-05-09 17:00 -07:00

moment

(

d

).

format

(

"YYYY-MM-DD HH:mm [UTC]Z"

);

// "1930-05-09 17:00 UTC-07:00

moment

(

d

).

format

(

"dddd, MMMM [the] Do, YYYY"

);

// "Friday, May the 9th, 1930"

moment

(

d

).

format

(

"h:mm a"

);

// "5:00 pm"

This example shows how inconsistent and inflexible the built-in date formatting

options are. In JavaScript’s favor, these built-in formatting options do attempt to pro‐

vide formatting that’s appropriate for the user’s locale. If you need to support date for‐

matting in multiple locales, this is an inexpensive but inflexible way to do it.
This is not designed to be an exhaustive reference to the formatting options available

in Moment.js; see the online documentation for that. What it is designed to commu‐

nicate is that if you have date formatting needs, Moment.js can almost certainly meet

them. Like many such date formatting metalanguages, there are some common con‐

ventions. More letters means more verbose; that is,

"M"

gets you

1

,

2

,

3

,...;

"MM"

gets

you

01

,

02

,

03

,...;

"MMM"

gets you

Jan

,

Feb

,

Mar

,...; and

"MMMM"

gets you

January

,

Febru

ary

,

March

,.... A lowercase

"o"

will give you an ordinal:

"Do"

will give you

1st

,

2nd

,

3rd

, and so on. If you want to include letters that you don’t want interpreted as meta‐

characters, surround them with square brackets:

"[M]M"

will give you

M1

,

M2

, and so

on.

One frustration that Moment.js doesn’t completely solve is the use

of time zone abbreviations, such as EST and PST. Moment.js has

deprecated the z formatting character due to lack of consistent

international standards. See the Moment.js documentation for a

detailed discussion of the issues with time zone abbreviations.

Date Components

If you need to access individual components of a

Date

instance, there are methods for

that:

const

d

=

new

Date

(

Date

.

UTC

(

1815

,

9

,

10

));

// these are the results someone would see in Los Angeles

d

.

getFullYear

()

// 1815

d

.

getMonth

()

// 9 - October

d

.

getDate

()

// 9

d

.

getDay

()

// 1 - Monday

Date Components | 225

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.