Date.UTC
takes all the same variations of arguments as the Date
constructor, but instead of returning a new Date instance, it returns
the numeric value of the date. That number can then be passed into
the Date constructor to create a date instance.
If you need to construct dates on the server that are in a specific time zone (and don’t
want to do the time zone conversion by hand), you can use
moment.tz
to construct
Date
instances using a specific time zone:
// passing an array to Moment.js uses the same parameters as JavaScript's Date
// constructor, including zero-based moths (0=Jan, 1=Feb, etc.). toDate()
// converts back to a JavaScript Date object.
const
d
=
moment
.
tz
([
2016
,
3
,
27
,
9
,
19
],
'America/Los_Angeles'
).
toDate
();
Constructing Dates in the Browser
Generally, JavaScript’s default behavior is appropriate in the browser. The browser
knows from the operating system what time zone it’s in, and users generally like to
work in local time. If you’re building an app that needs to handle dates in other time
zones, then you’ll want to use Moment.js to handle the conversion and display of
dates in other time zones.
Transmitting Dates
Where things get interesting is transmitting dates—either the server sending dates to
the browser or vice versa. The server and browser could be in different time zones,
and users want to see dates in their local time zone. Fortunately, because JavaScript
Date
instances store the date as a numeric offset from the UTC, Unix Epoch, it’s gen‐
erally safe to pass
Date
objects back and forth.
We’ve been talking about “transmitting” very vaguely, though: what exactly do we
mean? The surest way to ensure that dates are transmitted safely in JavaScript is using
JavaScript Object Notation (JSON). The JSON specification doesn’t actually specify a
data type for dates, which is unfortunate, because it prevents symmetric parsing of
JSON:
const
before
=
{
d
:
new
Date
() };
before
.
d
instanceof
date
// true
const
json
=
JSON
.
stringify
(
before
);
const
after
=
JSON
.
parse
(
json
);
after
.
d
instdanceof
date
// false
typeof
after
.
d
// "string"
So the bad news is that JSON can’t seamlessly and symmetrically handle dates in Java‐
Script. The good news is that the string serialization that JavaScript uses is always
consistent, so you can “recover” a date:
Transmitting Dates | 223