在項目需要一個計時器,效果如下:
js代碼:
復制代碼 代碼如下:
/*獲取當前時間*/
function getCurrentDate()
{
var timeStr = '';
var curDate = new Date();
var curMonth = curDate.getMonth()+1; //獲取當前月份(0-11,0代表1月)
var curDay = curDate.getDate(); //獲取當前日(1-31)
var curWeekDay = curDate.getDay(); //獲取當前星期X(0-6,0代表星期天)
var curHour = curDate.getHours(); //獲取當前小時數(0-23)
var curMinute = curDate.getMinutes(); // 獲取當前分鐘數(0-59)
var curSec =curDate.getSeconds(); //獲取當前秒數(0-59)
timeStr = curMonth+'月'+curDay+'日 周';
switch(curWeekDay)
{
case 0:timeStr += '日';break;
case 1:timeStr += '一';break;
case 2:timeStr += '二';break;
case 3:timeStr += '三';break;
case 4:timeStr += '四';break;
case 5:timeStr += '五';break;
case 6:timeStr += '六';break;
}
if(curHour < 10)
{
if(curMinute < 10)
{
if(curSec < 10)
{
timeStr += ' 0'+curHour+':0'+curMinute+':0'+curSec;
}
else
{
timeStr += ' 0'+curHour+':0'+curMinute+':'+curSec;
}
}
else
{
if(curSec < 10)
{
timeStr += ' 0'+curHour+':'+curMinute+':0'+curSec;
}
else
{
timeStr += ' 0'+curHour+':'+curMinute+':'+curSec;
}
}
}
else
{
if(curMinute < 10)
{
if(curSec < 10)
{
timeStr += ' '+curHour+':0'+curMinute+':0'+curSec;
}
else
{
timeStr += ' '+curHour+':0'+curMinute+':'+curSec;
}
}
else
{
if(curSec < 10)
{
timeStr += ' '+curHour+':'+curMinute+':0'+curSec;
}
else
{
timeStr += ' '+curHour+':'+curMinute+':'+curSec;
}
}
}
$("#time").text(timeStr);
}
然後條用這個函數就行。
最後,對Javascript日期的部分函數做個小結:
var myDate = new Date();
myDate.getYear(); //獲取當前年份(2位)
myDate.getFullYear(); //獲取完整的年份(4位,1970-????)
myDate.getMonth(); //獲取當前月份(0-11,0代表1月)
myDate.getDate(); //獲取當前日(1-31)
myDate.getDay(); //獲取當前星期X(0-6,0代表星期天)
myDate.getTime(); //獲取當前時間(從1970.1.1開始的毫秒數)
myDate.getHours(); //獲取當前小時數(0-23)
myDate.getMinutes(); //獲取當前分鐘數(0-59)
myDate.getSeconds(); //獲取當前秒數(0-59)
myDate.getMilliseconds(); //獲取當前毫秒數(0-999)
myDate.toLocaleDateString(); //獲取當前日期
var mytime=myDate.toLocaleTimeString(); //獲取當前時間
myDate.toLocaleString( ); //獲取日期與時間