- <div id="divTimeRemains">xxxx</div>
- <script language="JavaScript" type="text/javascript">
- String.prototype.leftPad = function(n, s) {
- ss = s || " ";
- if (this.length < n) {
- var ts = new Array(n - 1);
- ts[n - 1] = this;
- for (var i = 0; i < n - this.length; i++) {
- ts[i] = s;
- }
- return ts.join("");
- } else {
- return this;
- }
- }
- Date.prototype.format = function(style) {
- var o = {
- "M+" : this.getMonth() + 1, //month
- "d+" : this.getDate(), //day
- "h+" : this.getHours(), //hour
- "m+" : this.getMinutes(), //minute
- "s+" : this.getSeconds(), //second
- "w+" : "/u65e5/u4e00/u4e8c/u4e09/u56db/u4e94/u516d".charAt(this.getDay()), //week
- "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter
- "S" : this.getMilliseconds() //millisecond
- }
- if (/(y+)/.test(style)) {
- stylestyle = style.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
- }
- for(var k in o){
- if (new RegExp("("+ k +")").test(style)){
- stylestyle = style.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
- }
- }
- return style;
- };
- //script's begin...
- var timeEnd = new Date(2009, 3, 27, 9, 0, 0);
- function showRemainsTime(){
- var timeNow = new Date();
- var timeRemains = timeEnd - timeNow;
- var rs = [];
- rs[rs.length] = "距离";
- rs[rs.length] = timeEnd.format("yyyy年MM月dd日h点还有:");
- rs[rs.length] = Math.floor(timeRemains/(1000 * 60 * 60 * 24));
- rs[rs.length] = "天";
- rs[rs.length] = (Math.floor(timeRemains/(1000 * 60 * 60)) % 24).toString().leftPad(2, "0");
- rs[rs.length] = "小时";
- rs[rs.length] = (Math.floor(timeRemains/(1000 * 60)) % 60).toString().leftPad(2, "0");
- rs[rs.length] = "分";
- rs[rs.length] = (Math.floor(timeRemains/1000) % 60).toString().leftPad(2, "0");
- rs[rs.length] = "秒";
- document.getElementById("divTimeRemains").innerHTML = rs.join("");
- setTimeout("showRemainsTime()",1000);
- }
- showRemainsTime();
- //script's end...
- </script>
速度和效率应该都还行吧。想再快点,可以把1000 * 60 * 60这些值算出来。没算的原因是便于理解。采用了数组join的方式来提高字符串组合的速度。