Sharpen Your Saw 7

  1. The Presentation
  2. The Challenge
  3. Show and Tell

Working with dates and timezones in Javascript

A Survival Guide

https://github.com/moment/moment
https://github.com/date-fns/date-fns

Things Happen

Things Happen

> new Date("2020-01-08T19:47:00.000Z")
Wed Jan 08 2020 14:47:00 GMT-0500 (Eastern Standard Time)

// using moment.js
> moment("2020-01-08T19:47:00.000Z").format("h:mm a MMM DD, YYYY") 
"2:47 pm Jan 08, 2020"

// using date-fns
> format(parseISO("2020-01-08T19:47:00.000Z"), "h:mm a MMM dd, yyyy") 
"2:47 PM Jan 08, 2020"

Things Happen In Oslo

> new Date("2020-01-08T19:47:00.000Z")
Wed Jan 08 2020 20:47:00 GMT+0100 (Central European Standard Time)

// using moment.js
> moment("2020-01-08T19:47:00.000Z").format("h:mm a MMM DD, YYYY") 
"8:47 pm Jan 08, 2020"

// using date-fns
> format(parseISO("2020-01-08T19:47:00.000Z"), "h:mm a MMM dd, yyyy") 
"8:47 PM Jan 08, 2020"

Why Resist Localization?

Calendar Dates
Wall Time
> "Steve thinks 4:30 is too early"
"Steve thinks 4:30 is too early"

> moment.localizeThisSomehow("Steve thinks 4:30 is too early")
Uncaught TypeError: moment.localizeThisSomehow is not a function

Here's something to ruin your day

console.log(new Date("2020-01-01").toString());
// -> Tue Dec 31 2019 19:00:00 GMT-0500 (Eastern Standard Time)
console.log(format(new Date("2020-01-01"), "MMMM do yyyy"));
// -> December 31st 2019
// moment magically fixes this problem for you
console.log(moment("2020-01-01").format("MMMM Do YYYY"));
// -> January 1st 2020
// ... unless you invoke with a date and not a string
console.log(moment(new Date("2020-01-01")).format("MMMM Do YYYY"));
// -> December 31st 2019

Here's something to ruin your day v2

console.log(new Date("2020-01-01").toISOString());
// -> 2020-01-01T00:00:00.000Z

console.log(new Date("2020-01-01").toString());
// -> Tue Dec 31 2019 19:00:00 GMT-0500 (Eastern Standard Time)

Things to remember

  • Javascript always considers dates to be particular moments in time
  • They're stored as UTC but most methods automatically localize for you
  • Not every date is really something that happened at a particular moment in time
  • In these cases, the Javascript Date object often supplies too much or erroneous information

Part 2: The Challenge

https://shackbarth.github.io/sharpen-your-saw

Part 3: Show and Tell