after
.
d
=
new
Date
(
after
.
d
);
after
.
d
instanceof
date
// true
No matter what time zone was originally used to create the date, when it is encoded
as JSON, it will be in UTC, and when the JSON-encoded string is passed to the
Date
constructor, the date will be displayed in the local time zone.
The other safe way to pass dates between client and server is to simply use the
numeric value of the date:
const
before
=
{
d
:
new
Date
().
valueOf
() };
typeof
before
.
d
// "number"
const
json
=
JSON
.
stringify
(
before
);
const
after
=
JSON
.
parse
(
json
);
typeof
after
.
d
// "number"
const
d
=
new
Date
(
after
.
d
);
While JavaScript is happily consistent when JSON-encoding dates
as strings, the JSON libraries provided by other languages and plat‐
forms are not. The .NET JSON serializers in particular wrap JSON-
encoded date objects in their own proprietary format. So if you’re
interfacing with JSON from another system, take care to under‐
stand how it serializes dates. If you have control over the source
code, this is an instance where it may be safer to transmit numeric
dates as offsets from the Unix Epoch. Even here you must be care‐
ful, however: often date libraries will give the numeric value in sec‐
onds, not milliseconds.
Displaying Dates
Formatting dates for display is often one of the most frustrating problems for begin‐
ners. JavaScript’s built-in
Date
object includes only a handful of prepackaged date for‐
mats, and if they don’t meet your needs, it can be painful to do the formatting
yourself. Fortunately, Moment.js excels in this area, and if you are particular about
how dates are displayed, then I recommend you use it.
To format a date with Moment.js, use its
format
method. This method takes a string
with metacharacters that are replaced with the appropriate component of the date.
For example, the string
"YYYY"
will be replaced with the four-digit year. Here are
some examples of date formatting with the
Date
object’s built-in methods, and the
more robust Moment.js methods:
const
d
=
new
Date
(
Date
.
UTC
(
1930
,
4
,
10
));
// these show output for someone in Los Angeles
d
.
toLocaleDateString
()
// "5/9/1930"
d
.
toLocaleFormat
()
// "5/9/1930 4:00:00 PM"
224 | Chapter 15: Date and Time