0

I am using moment.js to show the time elapsed from 'today' to when a post(s) was published, for any post with the original ISO date '.iso-date' and then output the amount of time from the post in a div '.display-date'. I have a script that works ok, but it only shows 'years' and if the post is today then it outputs nothing. Similarly, it only shows months and then years after the first 12 months, so 1-11 months and then only x years ago.

Current output 'Posted 3 months ago', 'Posted a year ago', 'Posted e years ago' etc

So what I want to see is something like 'Posted Just Now', 'Posted Today', 'Posted 6 days ago', 'Posted 3 weeks, 5 days ago', Posted 9 months, 3 weeks, 5 days ago' and 'Posted 3 years, 9 months, 3 weeks, 5 days ago ' - or perhaps just 'the nearest date interval'.

Markup Example

<div class="posts-list">

<div class="grid-block">
<div class="iso-date">2019-09-30</div>
<div class="display-date"></div>
</div>

<div class="grid-block">
<div class="iso-date">2020-07-12</div>
<div class="display-date"></div>
</div>

</div>

Here is the current script:-

// Moment 
$(document).ready(function () {

// Moment targets
  var publishedDate = ".iso-date";
  var displayDate = ".display-date";
  
  $(publishedDate).each(function (i, e) {
  
    var p = $(e).text();
    var a = $(e).next(displayDate);
    
    if (moment(p).isValid()) {
    
   var m = moment(new Date(p));
   var s = moment(new Date(m)).fromNow();
    // var s = moment(new Date(m)).diff(moment(), 'milliseconds');  

      a.text("Posted " + s);
    }

  });

});

I would appreciate your input on how to achieve this with Moment.js r perhaps without any script dependencies - jQuery / JavaScript.

Thanks

Glennyboy

glennyboy
  • 153
  • 2
  • 15
  • Read this first [project-status](https://momentjs.com/docs/#/-project-status/recommendations/) and this [twitter](https://twitter.com/addyosmani/status/1304676118822174721) and think about whether you need such a huge library. – Grzegorz T. Apr 01 '21 at 19:36

1 Answers1

1

Check the below snippets. I used this answer from here and implemented it as per your requirements.

function dateAgo(date) {  

    var startDate = new Date( date + " " + '12:00 AM');
    var endDate = new Date();

    var diffDate  = new Date(new Date() - startDate);

    var yearDiff  = diffDate.toISOString().slice(0, 4) - 1970;
    var monthDiff = diffDate.getMonth(); 
    var dayDiff   = diffDate.getDate()-1;

    var msec  = endDate - startDate;
    var mins  = Math.floor(msec / 60000);
    var hrs   = Math.floor(mins / 60);
    var days  = Math.floor(hrs / 24);
      
    var label = 'Posted ';
    if( mins <= 30 ){
        label += ' Just Now';
    }else if( hrs <= 24 ){
        label += ' Just Today';
    }else{
        if( yearDiff > 0  ){
            label += ( yearDiff > 1 ) ? yearDiff+' years, ' : yearDiff+' year, ';
        }

        if( monthDiff > 0 ){
            label += ( monthDiff > 1 ) ? monthDiff+' months, ' : monthDiff+' month, ';
        }

        if( dayDiff > 0 ){
            label += ( dayDiff > 1 ) ? dayDiff+' days ' : dayDiff+' day ';
        }

        label += 'ago';
    }
  
    return label;   
    
}

(function() {
    var elements = document.body.getElementsByClassName('iso-date');
    for (var i = 0; i < elements.length; i++) {
        var date  = elements[i].innerHTML;
        var label = dateAgo(date);
        elements[i].nextElementSibling.innerHTML = label;   
    }
})();
<div class="grid-block">
<div class="iso-date">2019-09-30</div>
<div class="display-date"></div>
</div>

<div class="grid-block">
<div class="iso-date">2021-04-06</div>
<div class="display-date"></div>
</div>
Bhautik
  • 11,125
  • 3
  • 16
  • 38
  • Hi @Bhautik thanks for your original answer, which I appreciate is better as it doesn't use an external library. This works on individual post pages, but no within looped posts and I realise that wasn't obvious in my example. So how do I get this to work for 'each' instance of 'grid-block' within the parent '.posts-list'? So in reality the full (updated) markup is:-
    2019-09-30
    2019-09-30
    – glennyboy Apr 02 '21 at 09:42
  • Can you put HTML in your question with expected output. – Bhautik Apr 02 '21 at 09:49
  • My apologies, scrub the above. It seems to be working now. The only thing... any way to change the output on singular day(s), month(s), year(s). So, for example, instead of 'Posted 1 days ago' it reads 'Posted 1 day ago', similarly Posted 1 month ago etc. Thanks – glennyboy Apr 02 '21 at 10:06
  • Great, any way to remove the leading ',' for 1 day "Posted 1 day, ago"? – glennyboy Apr 02 '21 at 10:58
  • sorry for the delay, it's a holiday here :-) I just ran a test and it's not quite on the money just yet. I just posted and it says "Posted ago". I think one more mod to say 'Posted Just Now' + 'Posted Today' - can this be achieved? Thanks – glennyboy Apr 05 '21 at 10:47
  • `Posted Just Now` + `Posted Today` depends on what time diff? Example. post surpass 9min after you posted what will be a message to show? and same for `Posted Today` – Bhautik Apr 05 '21 at 10:57
  • lets' say 'Just now' is up to 30 minutes ago, and then anything else is 'Today' - make sense? – glennyboy Apr 06 '21 at 13:19
  • Yes, I will update my answer later. – Bhautik Apr 06 '21 at 13:31
  • big thumbs up from me! – glennyboy Apr 06 '21 at 17:57
  • Welcome... If this answer helps you then you can [accept](https://stackoverflow.com/help/someone-answers) the answer, and if you like/want you can also [upvote](https://stackoverflow.com/help/someone-answers) the answer too, Thanks. – Bhautik Apr 06 '21 at 17:57