Sometimes we need to know how many days between two dates, how many hours, or even how many minutes in seconds. Here we use JavaScript to implement a function to calculate the time difference of two dates, first look at the code:
01 |
<script type= "text/javascript" > |
06 |
Date.prototype.format = function (format){ |
08 |
* eg:format="YYYY-MM-dd hh:mm:ss"; |
11 |
"M+" : this .getMonth()+1, //month |
12 |
"d+" : this .getDate(), //day |
13 |
"h+" : this .getHours(), //hour |
14 |
"m+" : this .getMinutes(), //minute |
15 |
"s+" : this .getSeconds(), //second |
16 |
"q+" : Math.floor(( this .getMonth()+3)/3), //quarter |
17 |
"S" : this .getMilliseconds() //millisecond |
20 |
if (/(y+)/.test(format)) { |
21 |
format = format.replace(RegExp.$1, ( this .getFullYear()+ "" ).substr(4 - RegExp.$1.length)); |
25 |
if ( new RegExp( "(" + k + ")" ).test(format)) { |
26 |
format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ( "00" + o[k]).substr(( "" + o[k]).length)); |
34 |
* 获得时间差,时间格式为 年-月-日 小时:分钟:秒 或者 年/月/日 小时:分钟:秒 |
35 |
* 其中,年月日为全格式,例如 : 2010-10-12 01:00:00 |
39 |
function GetDateDiff(startTime, endTime, diffType) { |
40 |
//将xxxx-xx-xx的时间格式,转换为 xxxx/xx/xx的格式 |
41 |
startTime = startTime.replace(/\-/g, "/" ); |
42 |
endTime = endTime.replace(/\-/g, "/" ); |
45 |
diffType = diffType.toLowerCase(); |
46 |
var sTime = new Date(startTime); //开始时间 |
47 |
var eTime = new Date(endTime); //结束时间 |
61 |
divNum = 1000 * 3600 * 24; |
66 |
return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum)); |
69 |
var testDate = new Date(); |
70 |
var testStr = testDate.format( "yyyy-MM-dd hh:mm:ss" ); |
72 |
var result = GetDateDiff( "2010-02-26 16:00:00" , testStr, "day" ); |
73 |
document.write( "简明现代魔法 www.nowamagic.net 建站已有" + result + "天了。" ); |
The method used is simple, such as calculating the number of days to do this:
1 |
GetDateDiff( "2010-02-26 16:00:00" , "2011-07-02 21:48:40" , "day" ); |
The number of seconds can be calculated as follows:
1 |
GetDateDiff( "2010-02-26 16:00:00" , "2011-07-02 21:48:40" , "second" ); |
The operating result of the instance program is as follows: Guangde County Energy Bureau
The Concise modern Magic Www.nowamagic.net station has been built for 1695 days.
How JavaScript calculates the time difference between two days