Time ago snippet guide

This quick guide shows how to create a JavaScript snippet that converts date times into hours, days, minutes, and seconds from the current moment.

Steps

  1. Create a Budibase internal table that includes a date field. In this example, it is based on a blog.

  2. Add data to your table.

  3. Go to the design screen and add a Card block

  4. Fill in the relevant bindings for Title, description, and other fields.

  5. Go to the subtitle bindable area.

  6. Switch the tab from text to JavaScript.

  7. Click the </> icon and create a new snippet called timeago.

  8. Paste the code below into it and click save.

return function(pastTimeString) {
    const pastTime = new Date(pastTimeString);
    const now = new Date();
    const delta = now - pastTime;

    const days = Math.floor(delta / (1000 * 60 * 60 * 24));
    const hours = Math.floor((delta % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((delta % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((delta % (1000 * 60)) / 1000);

    const timeStrings = [];
    if (days > 0) {
        timeStrings.push(`${days} days`);
    }
    if (hours > 0) {
        timeStrings.push(`${hours} hours`);
    }
    if (minutes > 0) {
        timeStrings.push(`${minutes} minutes`);
    }
    if (seconds > 0) {
        timeStrings.push(`${seconds} seconds`);
    }

    if (timeStrings.length === 0) {
        return "just now";
    } else if (timeStrings.length === 1) {
        return timeStrings[0];
    } else {
        return timeStrings.slice(0, -1).join(', ') + ', and ' + timeStrings.slice(-1) + ' ago';
    }
}
  1. Click the snippet and add the date binding you want to use inside its brackets.
  2. Click save.

The end result


Did this page help you?