0

I'm using a mysql timestamp to calculate the difference of time through JavaScript as below,

function parseMySQLTimestamp(timestamp) {
    var parts = timestamp.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/);
    return new Date(+parts[1], (+parts[2] - 1), +parts[3], +parts[4], +parts[5], +parts[6]);
}




var informTime = "2011-11-09 08:00:00";
  var diff = (new Date()- parseMySQLTimestamp(informTime));

  var months = Math.floor(diff /(60*60*24*30*1000));
  diff=Math.abs(diff-(months*60*60*24*30*1000)); 
  var days = Math.floor(diff/(60 * 60 * 24*1000));
  diff=Math.abs(diff-(days*60*60*24*1000)); 
  var hour=Math.floor(diff/(60*60*1000));
  diff=Math.abs(diff-(hour*60*60*1000)); 
  var minute=Math.floor(diff/(60*1000));

  var message=months +" months "+ days + " D " + hour + " Hr " + minute + "min ago ";
  alert(message);

it will give the correct result but I'm afraid that it will not be correct in the months which have 31,28 or 29 days other wise in leap years.

How to achieve reliable functionality? I feel it's so complicated. Thank you.

VMai
  • 10,156
  • 9
  • 25
  • 34
kbitsoft
  • 61
  • 1
  • 10
  • Have a look at http://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript best voted answer and include http://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript/15289883#15289883 to resolve the daylight savings time problem. – VMai Jun 20 '14 at 12:36
  • How about using the MySQL function [DATE_FORMAT](https://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_date-format) so you can parse your timestamp more easily? – VMai Jun 20 '14 at 12:38
  • pls consider i want calculate difference between two dates. ex:1Months2 days3 Hour 4 minute ago ** – kbitsoft Jun 21 '14 at 10:59
  • I considered this in my first comment. http://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript shows you how to calculate months and even years. The only flaw would be the daylight savings time problem. Best use UTC time only. – VMai Jun 21 '14 at 11:04

0 Answers0