In Defense of JavaScript's Date Class

#73・
1.26K

subscribers

83

issues

Subscribe to our newsletter

By subscribing, you agree with Revue’s Terms of Service and Privacy Policy and understand that Mastering JS Weekly will receive your email address.

In Defense of JavaScript's Date Class
By Mastering JS Weekly • Issue #73 • View online
JavaScript’s `Date` class sometimes seems to be universally disliked. For many years, I reached for Moment.js the instant I needed to do anything more than store a date in the database. But now, as I’ve started working more with various alternatives like date-fns and the temporal API, I’ve come to appreciate JavaScript’s Date class a lot more.
Like JavaScript itself, the Date class is certainly quirky, but filled with delightful surprises that make it easier to work with than most devs would believe. Here’s a few neat lessons I’ve learned working with the Date class in recent months.

Comparing and Sorting Dates
Oddly enough, the < and > comparison operators work with JavaScript dates. And subtracting two dates returns the difference between the two dates in milliseconds. So comparing dates in JavaScript is actually very easy.
Comparing dates in JS
Comparing dates in JS
That makes sorting arrays of dates, or sorting arrays of objects by a date property, extremely easy.
Sorting an array of objects by `createdAt`
Sorting an array of objects by `createdAt`
Just the Date, No Time
Sometimes you want to compare just the date portion of two dates. So compare two dates for equality, excluding time. The way to do this is to zero out the two dates’ hours, minutes, seconds, and milliseconds. You can do this by calling `setHours(0)`, `setMinutes(0)`, `setSeconds(0)`, and `setMilliseconds(0)`.
Zeroing out the time is tricky with `setHours()`, etc.
Zeroing out the time is tricky with `setHours()`, etc.
But that’s unfortunately a bit too verbose. Thankfully, `setHours()` supports a neat shorthand that lets you set hours, minutes, seconds, and milliseconds with one function call.
Much easier with just one `setHours()` call!
Much easier with just one `setHours()` call!
Similarly, you can do the same thing with `.setFullYear()` to set the year, month, and date if you want to compare just the time components of a date.
Removing the date component, just leaving the time component
Removing the date component, just leaving the time component
YYYYMMDD in Vanilla JS Made Easy
JavaScript has `toLocaleString()` and `toLocaleDateString()` functions that let you do some basic date formatting in vanilla JavaScript. One of the most basic date formatting tasks is converting a date to a YYYYMMDD string: 4 digit year, 2 digit month, 2 digit day.
Unfortunately, converting to YYYYMMDD in vanilla JavaScript is tricky because getting 2 digit month and day is not obvious. One approach is to pad yourself, which is readable but somewhat cumbersome.
Works, but somewhat clunky
Works, but somewhat clunky
There is a slightly more clever approach that is a one-liner though. The `toLocaleDateString()` function takes a locale parameter, and some locales output dates in friendlier formats. In particular, the en-GB locale outputs date strings in DD/MM/YYYY format, with 2 digit days and months. So with a little bit of `split()` and `join()` you can convert en-GB date strings into YYYYMMDD:
One-line YYYYMMDD. Too clever for production code?
One-line YYYYMMDD. Too clever for production code?
Basic Formatting and Timezones
The `toLocaleDateString()` function and the closely related `toLocaleString()` methods both support a timezone option. That means you can use the above function to convert to YYYYMMDD in arbitrary timezones with no outside libraries. No moment-timezone required!
YYYYMMDD, plus custom timezones
YYYYMMDD, plus custom timezones
Similarly, `toLocaleString()` lets you format dates in custom timezones, with custom arguments.
Date formatting using `toLocaleString()`
Date formatting using `toLocaleString()`
The `toLocaleString()` function can substitute for a full date formatter in a few situations. But unfortunately it comes with a huge limitation: there’s no way to change the order of the components without changing the locale. There’s another reason why we had to use the en-GB locale: because that locale happens to output year, month, date in exactly the opposite order of what we needed.
So while `toLocaleString()` and `toLocaleDateString()` can help you solve some limited basic problems without reaching for an outside lib, odds are you should use an outside lib if you have anything beyond the most basic of date formatting requirements. Otherwise you might find yourself trying to figure out the exact right locale to get dates into the format you need.
Most Recent Tutorials
How to Compare Dates Without Time in JavaScript - Mastering JS
How to Trim Characters from a String in JavaScript - Mastering JS
Using Query String Parameters in Mongoose - Mastering JS
How to Use Mongoose's findOneAndUpdate Function - Mastering JS
Make Mongoose's findOneAndUpdate() Return the Updated Document - Mastering JS
How to Sort an Array by Date in JavaScript - Mastering JS
What We're Reading
High-performance Cross-domain Events Tracking – Hello, I'm Alex
Is Deno Still a Thing? A Look at the Status of the Node Killer | by Fernando Doglio | Oct, 2021 | Bits and Pieces
Did you enjoy this issue?
Mastering JS Weekly

Pragmatic web development. No bloatware allowed!

In order to unsubscribe, click here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue