When Yesterday Isn't Yesterday

The typical toddler can adequately describe the concept of yesterday, but in software development it's not always as easy as "the day before today." First of all, today is relative. No matter where you are in the world, someone is either lagging behind in yesterday or plowing ahead in tomorrow. Since an internet user can be located anywhere, web software needs to be either flexible enough to adapt to the location of each user or it shouldn't use relative terms like "today" and "tomorrow."

A perfect example of getting this wrong is Stack Overflow. First of all, I'm a huge fan of the site. I think it's genius and I'm jealous I didn't create it first. That being written, it gets the "today" and "yesterday" thing wrong. Until 24 hours have passed since the time a question was asked, the website will show that the question was asked today. While I doubt it's the type of bug that would keep astronauts from the moon, it's weird. I even brought it up a while back on the UserVoice suggestions list and was shot down by Jeff Atwood himself. The reason? Evidently it's that way "by design."

I'm not someone who likes to criticize without providing either sympathy or preferably a possible solution so below you'll find the JavaScript necessary to convert yesterday's date into the string "yesterday." In order for the script to function, you need to output the date into an HTML element in a format that JavaScript can parse into a Date object. Then, just mark the containing element with the CSS class "ReplaceDate" and the date will be replaced if applicable. Since the conversion happens on the client side, the yesterday problem should take care of itself naturally (provided that the user has their date set properly). Lastly, the script should degrade gracefully such that the original dates sent to the client are displayed to the user.

Warning: This was whipped up in Notepad and tested briefly in IE8. There are no guarantees that this code will work properly. In fact, the code is probably ugly enough to make babies cry.

$(document).ready(function() {
    var yesterday = new Date();

    $('.ReplaceDate').each(function() {
        var elementDate = new Date($(this).text());

        if (elementDate.getDate() === yesterday.getDate() && 
            elementDate.getMonth() === yesterday.getMonth() && 
            elementDate.getFullYear() === yesterday.getFullYear()) {


blog comments powered by Disqus