Home >Web Front-end >JS Tutorial >Javascript calculation time difference function written by myself_javascript skills

Javascript calculation time difference function written by myself_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:18:39983browse

I wrote it myself, it’s just applicable, not very good, it should still be optimized. Record it yourself first. Stop talking nonsense, it’s best to post the code directly:

Copy the code The code is as follows:

/ *
* Get the time difference, the time format is year-month-day hour:minute:second or year/month/day hour:minute:second
* Among them, year, month and day 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)
{
//Replace xxxx -xx-xx time format, converted to xxxx/xx/xx format
startTime = startTime.replace(/-/g, "/");
endTime = endTime.replace(/-/g, "/");

//Convert calculated interval characters to lowercase
diffType = diffType.toLowerCase();

var sTime = new Date(startTime); //Start time
var eTime = new Date(endTime); //End time

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


The calling method is also very simple:
GetDateDiff("2010-10-11 00:00:00", "2010-10-11 00:01:40", "day")

This is Calculate the number of days
GetDateDiff("2010-10-11 00:00:00", "2010-10-11 00:01:40", "seond") is the calculation of the number of seconds

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn