最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How I can calculate an elapsed time between two date objects in Ionic? - Stack Overflow

programmeradmin1浏览0评论

I have a date object created from vars saved in a database.

var prevdate = yyyy-mm-dd hh:mm:ss;

I want to calculate with current time (date now ()) and want show to list on my Ionic app like my concept below such as "2 days ago" or "A moment ago" or "One hour ago". How I can achieve it?

I have a date object created from vars saved in a database.

var prevdate = yyyy-mm-dd hh:mm:ss;

I want to calculate with current time (date now ()) and want show to list on my Ionic app like my concept below such as "2 days ago" or "A moment ago" or "One hour ago". How I can achieve it?

Share Improve this question edited Jun 24, 2015 at 23:56 user3077416 asked Jun 24, 2015 at 23:43 user3077416user3077416 2712 gold badges10 silver badges31 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Try this

var past=new Date('2015-06-24 19:57:00');
var now= new Date();
var diff=msToTime(now-past);

console.log(diff.toString());

function msToTime(s) {
  var ms = s % 1000;
  s = (s - ms) / 1000;
  var secs = s % 60;
  s = (s - secs) / 60;
  var mins = s % 60;
  var hrs = (s - mins) / 60;
  if(hrs==0 && mins==0)
      return 'just a moment ago';
  else if(hrs==0)
      return mins+' mins ago';
  else if(hrs<24)
      return hrs+' hours ago';
  else
      return Math.floor(hrs/24)+' days ago';
}

Try out changing out the past var to see various results.

Its better to use http://momentjs./ for date manipulation using js. It provides most of the features we need related with date. You can get the date difference on moment using

moment('2015-06-24 19:57:00', "YYYYMMDD").fromNow();

here is an example of time delta. Time difference in Nodejs?

then create a function as previous answer suggested to make decision on what to return as string.

发布评论

评论列表(0)

  1. 暂无评论