在项目需要一个计时器,效果如下:
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
{
if(curMinute
{
if(curSec
{
timeStr += ' 0'+curHour+':0'+curMinute+':0'+curSec;
}
else
{
timeStr += ' 0'+curHour+':0'+curMinute+':'+curSec;
}
}
else
{
if(curSec
{
timeStr += ' 0'+curHour+':'+curMinute+':0'+curSec;
}
else
{
timeStr += ' 0'+curHour+':'+curMinute+':'+curSec;
}
}
}
else
{
if(curMinute
{
if(curSec
{
timeStr += ' '+curHour+':0'+curMinute+':0'+curSec;
}
else
{
timeStr += ' '+curHour+':0'+curMinute+':'+curSec;
}
}
else
{
if(curSec
{
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( ); //获取日期与时间