1

I have a function, which is written in JavaScript for getting the date time in day/month/year hours/minutes/seconds AM/PM format. What I want is a function, which will allow me to return the string of the following type (1 second, or 5 seconds, or 2 minutes, or 4 hours, or 1 day, or 5 months, or 5 years). Here is a sample code snippet:

function (var inputDate)
{
    var difference = dateNow - inputDate;
    //1 second, or 5 seconds, or 2 minutes, or 4 hours, or 1 day, or 5 months, or 5 years - I want to return the highest difference between both dates (current date and the date, which I input)
    return string difference;
}

Thanks in advance!

pvarbanov
  • 13
  • 3

2 Answers2

1

Once again I'm late to the party but as @user1950292 suggests you can subtract two dates and format the difference. Something like:

function dateDiffString(a,b) {
    var diff = (a.getTime() - b.getTime());
    var diffs = {
        years  : Math.floor((diff) / (1000 * 60 * 60 * 24 * 365)),
        months : Math.floor((diff) / (1000 * 60 * 60 * 24 * 30)),
        weeks  : Math.floor((diff) / (1000 * 60 * 60 * 24 * 7)),
        days   : Math.floor((diff) / (1000 * 60 * 60 * 24)),
        hours  : Math.floor((diff) / (1000 * 60 * 60)),
        mins   : Math.floor((diff) / (1000 * 60)),
        secs   : Math.floor((diff) / (1000))
    }
    //iterate through diffs to find first number > 0
    for (var prop in diffs) {
       if(diffs.hasOwnProperty(prop) && diffs[prop] > 0){
          return diffs[prop] + " " + prop;
       }
    }
}

var today = new Date();
var anotherDay = new Date("2013 12 13,11:52:39");
alert(dateDiffString(today,anotherDay));

http://jsfiddle.net/xuqNt/

Moob
  • 14,420
  • 1
  • 34
  • 47
0

You can create two Date objects and substract them. Then get the days, hours, minutes, seconds of the result and choose which to output. I have no code atm, but the Date usage is quite intuitive.

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date

user1950929
  • 874
  • 1
  • 9
  • 17