A few notes on JavaScriptDate
object, based on trying to do some basic things with them in Observable notebooks.
I had date times that looked like this:
2022-03-05 14:35
Passing this string to theDate()
constructor breaks in interesting ways: it assumes they are in the browser's current timezone, and it breaks in Safari producing anInvalid Date
error.
This worked instead:
newDate(o.datetime.replace(" ","T")+":00Z"))
Safari requires dates to look like this - without theT
you getInvalid Date
:
2022-03-05T14:35:00Z
Adding the trailingZ
causes the date to be treated as if it was UTC. This can be helpful if you plan to work with them in a mostly timezone-unaware fashion, though see the note about using{timeZone: "UTC"}
with the formatting methods later in this document.
JavaScript date objects REALLY want to be helpful with timezones. Consider the following examples, here using.toString()
:
(newDate("2021-01-15T14:31:00")).toString()"Fri Jan 15 2021 14:31:00 GMT-0800 (Pacific Standard Time)"(newDate("2021-01-15T14:31:00Z")).toString()"Fri Jan 15 2021 06:31:00 GMT-0800 (Pacific Standard Time)"
In both cases the.toString()
method converts to my current timezone, Pacific Standard Time. Note how the one with theZ
gets displayed as06:31:00
while the one without theZ
is shown as14:31:00
.
I wanted to calculate the number of minutes difference between a start date and an end date. Subtracting the two gives you a difference between them as in integer number of milliseconds! So this gives you minutes:
letdiff=end.getTime()-start.getTime();letminutes=Math.round(diff/60*1000);
The closest JavaScript gets to Python's handystrftime() method is the much more unwieldlytoLocaleDateString()
method. Some examples:
(newDate).toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",})"Sunday, January 16, 2022"(newDate).toLocaleTimeString("en-US")"12:12:29 PM"
These are also timezone aware. PassingtimeZone: "UTC"
to them can be useful, for example:
// This outputs in my timezone, PST:(newDate("2021-01-22T15:03:00Z")).toLocaleTimeString("en-US")"7:03:00 AM"// This keeps the output in UTC:(newDate("2021-01-22T15:03:00Z")).toLocaleTimeString("en-US",{timeZone:"UTC"})"3:03:00 PM"
MDN documentation:
Lots of useful comments on this inreplies on Twitter, including recommendations for these libraries:
Created 2022-01-16T12:16:03-08:00, updated 2022-01-16T13:20:28-08:00 ·History ·Edit