Write their own Javascript to calculate the time difference function

  • 2020-03-26 21:44:44
  • OfStack

I wrote it down myself, it just works, it's not good, it should be able to optimize. Write it down for yourself. Don't talk nonsense, direct paste code is best:


/*
 *  Acquisition time difference , Time format is   years - month - day   hours : minutes : seconds   or   years / month / day   Hour: minute: second 
 *  The date, month and year are in full format, for example   :  2010-10-12 01:00:00
 *  The return precision is: seconds, minutes, hours, days 
 */
 function GetDateDiff(startTime, endTime, diffType)
{
    //Convert the time format of xxx-xx-xx to the format of XXXX /xx/xx
    startTime = startTime.replace(/-/g, "/");
    endTime = endTime.replace(/-/g, "/");

    //Converts the calculated interval class character to lowercase
    diffType = diffType.toLowerCase();
    var sTime = new Date(startTime);    //The start time
    var eTime = new Date(endTime);  //The end of time

    //A number used as a divisor
    var divNum = 1;
    switch (diffType)
    {
        case "second":
            divNum = 1000;
            break;
        case "minute":
            divNum = 1000 * 60;
            break;
        case "hour":
            divNum = 1000 * 3600;
            break;
        case "day":
            divNum = 1000 * 3600 * 24;
            break;
        default:
            break;
    }
    return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
}

Calling methods is also simple:
GetDateDiff("2010-10-11 00:00:00", "2010-10-11 00:01:40", "day")
This is counting days
GetDateDiff("2010-10-11 00:00:00", "2010-10-11 00:01:40", "seond") counts the number of seconds


Related articles: