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

I have a date object created from vars saved in a database.var prevdate = yyyy-mm-dd hh:mm:ss;I want to

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745228195a4617559.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信