LEARNING JAVASCRIPT - Trang 244

are represented by seconds, what date corresponds to 0? It isn’t, as it turns out, the

birth of Christ, but an arbitrary date: January 1, 1970, 00:00:00 UTC.
As you’re probably aware, the world is divided into time zones (TZs) so that, no mat‐

ter where you are in the morning, 7 A.M. is morning and 7 P.M. is evening. Time

zones can get complicated fast, especially as you start to consider daylight saving

time. I won’t attempt to explain all the nuances of the Gregorian calendar or time

zones in this book—Wikipedia does an excellent job of that. However, it’s important

to cover some of the basics to help us understand the JavaScript

Date

object (and

what Moment.js brings to the table).
All time zones are defined as offsets from Coordinated Universal Time (abbreviated

UTC—refer to Wikipedia for the complicated and somewhat hilarious reasons). UTC

is sometimes (and not entirely correctly) referred to as Greenwich Mean Time

(GMT). For example, I’m currently in Oregon, which is in the Pacific time zone.

Pacific time is either eight or seven hours behind UTC. Wait, eight or seven? Which is

it? Depends on the time of year. In the summer, it’s daylight saving time, and the off‐

set is seven. The rest of the year, it’s standard time, and the offset is eight. What’s

important here is not memorizing time zones, but understanding how the offsets are

represented. If I open up a JavaScript terminal, and type

new Date()

, I see the follow‐

ing:

Sat Jul 18 2015 11:07:06 GMT-0700 (Pacific Daylight Time)

Note that in this very verbose format, the time zone is specified both as an offset from

UTC (

GMT-0700

) and by its name (

Pacific Daylight Time

).

In JavaScript, all

Date

instances are stored as a single number: the number of millisec‐

onds (not seconds) since the Unix Epoch. JavaScript normally converts that number

to a human-readable Gregorian date whenever you request it (as just shown). If you

want to see the numeric representation, simply use the

valueOf()

method:

const

d

=

new

Date

();

console

.

log

(

d

);

// formatted Gregorian date with TZ

console

.

log

(

d

.

valueOf

());

// milliseconds since Unix Epoch

Constructing Date Objects

The

Date

object can be constructed in four ways. Without any arguments (as we’ve

seen already), it simply returns a

Date

object representing the current date. We can

also provide a string that JavaScript will attempt to parse, or we can specify a specific

(local) date down to the millisecond. Here are examples:

// all of the below are interpreted with respect to local time

new

Date

();

// current date

// note that months are zero-based in JavaScript: 0=Jan, 1=Feb, etc.

220 | 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.