Trouble with Dates
Written , a 2 minute read
I'm a long term fan of Gwern Branwen website. Not only their website has marvelous design, the content delivers too. One of the latest updates is an introduction of date range subscripts. This feature appends to dates a subscript that denotes how many years ago given date was. For detailed justification see fragment linked above but the gist of idea is the trouble that human brain seems to have with absolute units in relative contexts, like how long given date was. The mind seems to mix up things based on our particular experience with time, thus making absolute dates very unintuitive unit.
The page were I have a lot of dates is my diary/review page for movies and series. I mark each one with release year to differentiate similar titles and give quick sense of time context. Which makes this a perfect candidate for adding how many years ago subscripts.
Implementation
Three interesting challenges rise here:
- From what point we show those subscripts? If the current year is , seems quite natural for something that happened 4 years ago. Or does it? While calculation is quite simple, my brain doesn't do it and instead tells me that this number feels recently;
- I want this site to be multilingual - does the script needs to check page language? How many languages my implementation supports;
- How to recognize dates from other numbers.
While the first one is just based on vibes and testing, the second one is easily solvable.
From all major browsers support Intl.RelativeTimeFormat
, an API for creating this little strings:
> new Intl.RelativeTimeFormat('en').format(-3, 'year')
"3 years ago"
> new Intl.RelativeTimeFormat('de').format(-3, 'year')
"vor 3 Jahren"
> new Intl.RelativeTimeFormat('pl').format(-3, 'year')
"3 lata temu"
Which allows for showing this in localized form easily.
As for third point, I carefully choose which numbers get the subscript on the page.
In case of my media diary/reviews page the solution is to only modify in the specific part of title of each review.
That way, even movies with dates in titles don't get modified.
Another solution (done here) is to put dates in <time>
element (which is a nice thing to do anyway) and let JavaScript recognize them that way.
Since I'm a fan of RFC 3339, the dates will follow the shape that we can check with this regex /^([12]\d{3})(?:-[01]\d(?:-\d\d)?)?$/
(aka either yyyy or yyyy-mm or yyyy-mm-dd).
Some kind of deduplication mechanism should be nice. Readers will remember from the first time they read this date how long ago it was in the same article or on the same page. For more scattered content, like page consisting of separate posts it is not needed.
Below is the actual code that is used on this site (by making script tag visible):