-->

Livestamp Plugin Jquery - how to show a time?

2020-08-04 09:59发布

问题:

I use this jquery plugin: livestamp. If you know, tell please, how to show time (hours, minutes ago) only for the current day. After 24 hours on next day - to show label "yesterday" or simple date. Thank you!

回答1:

By default, I don't think livestamp can do this.

But, at the bottom of livestamp's examples, they have some code to animate the text when it changes by hooking into the change.livestamp event.

We can use moment.js to modify this code to do what you're asking.

$('#animation').on('change.livestamp', function(event, from, to) {
    event.preventDefault(); // Stop the text from changing automatically

    // Get the original timestamp out of the event
    var originalTS = event.timeStamp;
    // Make a new moment object to compare the timestamp to
    var newDate = moment();
    // Use moment's .diff method to get the ms difference between timestamps
    var delta = newDate.diff(originalTS);

    // If the difference is less than a day's worth of ms
    if (delta < 86400000){
        // Use formatted text provided by the change event
        $(this).html(to);
    }
    else {
        // Format the moment object with whatever moment format you want
        $(this).html( newDate.format("dddd M/D/YYYY") );
    }
}).livestamp();

I haven't used livestamp, but it seems to rely on moment existing for its formatting options, so this should just work.

Livestamp's source is super small, so consider hacking on it yourself if you have other stuff you want to be able to do.