VolkovLabs / volkovlabs-dynamictext-panel

Business Text Panel for @grafana
https://docs.volkovlabs.io
Apache License 2.0
78 stars 14 forks source link

Relative Time #251

Closed yoseif2 closed 6 months ago

yoseif2 commented 6 months ago

I want to display a time similar to the Grafana "From Now" Unit type and I see that Moment.js does have a fromNow() function, but it looks like the "date" handlebar helper only allows us to pass a format string. I thought I could create a custom handlebar helper, but it doesn't seem to be able to access the Moment.js library. Is there a way to make this work?

handlebars.registerHelper
  ("fromNow",
    (timestamp) => moment(timestamp).fromNow()
  );

Error: "moment is not defined"

mikhail-vl commented 6 months ago

@yoseif2 We don't expose moment library in the JS Code. Looking around I found this blog post: https://gomakethings.com/a-vanilla-js-alternative-to-the-moment.js-timefromnow-method/

I have not tried it, but seems to be a good alternative. Let me know if it works for you.

/*!
 * Get the amount of time from now for a date
 * (c) 2021 Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {String|Date} time The date to get the time from now for
 * @return {Object}           The time from now data
 */
function timeFromNow (time) {
    // Get timestamps
    let unixTime = new Date(time).getTime();
    if (!unixTime) return;
    let now = new Date().getTime();

    // Calculate difference
    let difference = (unixTime / 1000) - (now / 1000);

    // Setup return object
    let tfn = {};

    // Check if time is in the past, present, or future
    tfn.when = 'now';
    if (difference > 0) {
        tfn.when = 'future';
    } else if (difference < -1) {
        tfn.when = 'past';
    }

    // Convert difference to absolute
    difference = Math.abs(difference);

    // Calculate time unit
    if (difference / (60 * 60 * 24 * 365) > 1) {
        // Years
        tfn.unitOfTime = 'years';
        tfn.time = Math.floor(difference / (60 * 60 * 24 * 365));
    } else if (difference / (60 * 60 * 24 * 45) > 1) {
        // Months
        tfn.unitOfTime = 'months';
        tfn.time = Math.floor(difference / (60 * 60 * 24 * 45));
    } else if (difference / (60 * 60 * 24) > 1) {
        // Days
        tfn.unitOfTime = 'days';
        tfn.time = Math.floor(difference / (60 * 60 * 24));
    } else if (difference / (60 * 60) > 1) {
        // Hours
        tfn.unitOfTime = 'hours';
        tfn.time = Math.floor(difference / (60 * 60));
    } else {
        // Seconds
        tfn.unitOfTime = 'seconds';
        tfn.time = Math.floor(difference);
    }

    // Return time from now data
    return tfn;

}

console.log('now', timeFromNow(new Date()));
console.log('past', timeFromNow('April 4, 2017'));
console.log('future', timeFromNow('April 4, 2024'));
yoseif2 commented 6 months ago

It's working for me. Thanks for the guidance!

mikhail-vl commented 6 months ago

@yoseif2 Glad it worked!