Javascript时间操作小结

来源:http://www.ido321.com/847.html

在项目需要一个计时器,效果如下:

Javascript时间操作小结

js代码

   1: /*获取当前时间*/
   2: function getCurrentDate()
   3: {
   4:   var timeStr = '';
   5:   var curDate = new Date();
   6:   var curMonth = curDate.getMonth()+1;  //获取当前月份(0-11,0代表1月)
   7:   var curDay = curDate.getDate();       //获取当前日(1-31)
   8:   var curWeekDay = curDate.getDay();    //获取当前星期X(0-6,0代表星期天)
   9:   var curHour = curDate.getHours();      //获取当前小时数(0-23)
  10:   var curMinute = curDate.getMinutes();   // 获取当前分钟数(0-59)
  11:   var curSec =curDate.getSeconds();      //获取当前秒数(0-59)
  12:   timeStr = curMonth+'月'+curDay+'日 周';
  13:   switch(curWeekDay)
  14:   {
  15:     case 0:timeStr += '日';break;
  16:     case 1:timeStr += '一';break;
  17:     case 2:timeStr += '二';break;
  18:     case 3:timeStr += '三';break;
  19:     case 4:timeStr += '四';break;
  20:     case 5:timeStr += '五';break;
  21:     case 6:timeStr += '六';break;
  22:   }
  23:   if(curHour < 10)
  24:   {
  25:     if(curMinute < 10)
  26:     {
  27:       if(curSec < 10)
  28:       {
  29:         timeStr += ' 0'+curHour+':0'+curMinute+':0'+curSec;
  30:       }
  31:       else
  32:       {
  33:         timeStr += ' 0'+curHour+':0'+curMinute+':'+curSec;
  34:       }
  35:     }
  36:     else
  37:     {
  38:       if(curSec < 10)
  39:       {
  40:         timeStr += ' 0'+curHour+':'+curMinute+':0'+curSec;
  41:       }
  42:       else
  43:       {
  44:         timeStr += ' 0'+curHour+':'+curMinute+':'+curSec;
  45:       }
  46:     }
  47:   }
  48:   else
  49:   {
  50:     if(curMinute < 10)
  51:     {
  52:       if(curSec < 10)
  53:       {
  54:         timeStr += ' '+curHour+':0'+curMinute+':0'+curSec;
  55:       }
  56:       else
  57:       {
  58:         timeStr += ' '+curHour+':0'+curMinute+':'+curSec;
  59:       }
  60:     }
  61:     else
  62:     {
  63:       if(curSec < 10)
  64:       {
  65:         timeStr += ' '+curHour+':'+curMinute+':0'+curSec;
  66:       }
  67:       else
  68:       {
  69:         timeStr += ' '+curHour+':'+curMinute+':'+curSec;
  70:       }
  71:     }
  72:   }
  73:   $("#time").text(timeStr);
  74: }

然后条用这个函数就行。

最后,对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( );  //获取日期与时间

上一篇:数据人员Sql必会列转行


下一篇:SQL Server 2012 Features