admin管理员组

文章数量:1415139

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.

本文标签: javascriptHow I can calculate an elapsed time between two date objects in IonicStack Overflow