Ad

If Date Is Todays Date Display "today", Or "yesterday"

- 1 answer

In my Shopify blog I can display the date of the posted article by the following code:

{{ article.created_at | date: "%A, %-d. %B" }}

It displays like this: Friday, 22. January. See date desc from Shopify here.

Is it possible to make a script that checks if the date is today, then display the text "today" insted of the shopify date script? And "yesterday"?

Ad

Answer

There might be a built-in solution with Shopify, but if not, running this script after page load should give you a way to do what you want.

Note though, that the date to calc. need to have the year as well, or else it will go wrong.


Update after request to not show the year

To show the date without year, you could do like this instead, where you can format the visible date any way you like, as it uses the data-date value for calc.

A positive side effect with this is, that if you need the date it will still be there in the data-date attribute.

<span class="date" data-date='{{ article.published_at | date: "%F" }}'>{{ article.created_at | date: "%A, %-d. %B" }}</span>

Updated sample

function makeYMD(d) {
  return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
}
function getYesterday(d) {
  return new Date(d.setDate(d.getDate() - 1));
}

var span = document.querySelector('span.date');
var spandate = new Date(span.getAttribute("data-date"));
var today = new Date();
var yesterday = getYesterday(new Date());

spandate = makeYMD(spandate);
today = makeYMD(today);
yesterday = makeYMD(yesterday);


if(today == spandate) {
   span.textContent = "Today";
} else if(yesterday == spandate) {
   span.textContent = "Yesterday";
}
<span class="date" data-date='2016-01-31'>Monday, 31. January</span>

Ad
source: stackoverflow.com
Ad