Search code examples
jqueryajaxwordpresswordpress-rest-api

How To Change Wordpress REST API date into "time ago" format


Relatively new to using the Wordpress REST API. Learning as I code and have been reading tons of forums and tutorials, I've managed to code this get for a custom post type.

My issue is trying to get the ISO8601 timestamp to render as "xx ago".

I've looked into Moments.js & tried TimeAgo plugin; but not sure I'm understanding the languages correctly to apply the functions to my current code.

Any help is appreciated.

 <div id="wodfeed"></div>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>$.ajax({
  url: '/wp-json/wp/v2/memberworkouts',
  dataType: 'json',
  type: 'get',
  cache: false,
  success: function (data) { 
    $(data).each(function(index, value) {
      var jtitle = value.title.rendered;
      var jimg = value.featured_image;
      var jid = value.member_id;
      var jtime=value.modified;

      $('#wodfeed').append('<div><h3 id="prog_date"><time class="timeago" datetime="' + jtime + '"> ' + jtime + ' </time></h3><h1 class="member-id">@' + jid + '</h1><img class="memberwod" src="'+ jimg +'"><h2 class="post-title"><span class="namebefore">' + jid + ' completed: </span> ' + jtitle + '</h2></div>');
    });
  }
});</script>

Solution

  • Per @AswinKumar using Moments.js

    Pass as a new variable:

    moment(jtime).fromNow()
    

    Then call the new variable in the append

     success: function (data) { 
        $(data).each(function(index, value) {
          var jtitle = value.title.rendered;
          var jimg = value.featured_image;
          var jid = value.member_id;
          var jtime=value.modified;
          var jtimeago= moment(jtime).fromNow(); 
    
    
    
          $('#wodfeed').append('<div><h3 id="prog_date">' + jtimeago + '</h3><h1 class="member-id">@' + jid + '</h1><img class="memberwod" src="'+ jimg +'"><h2 class="post-title"><span class="namebefore">' + jid + ' completed: </span> ' + jtitle + '</h2></div>');
        });