1、JS中Date對象經常使用的方法html
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( ); //獲取日期與時間
2、js時間日期處理實例code
// 增長天 function AddDays(date,value) { date.setDate(date.getDate()+value); } // 增長月 function AddMonths(date,value) { date.setMonth(date.getMonth()+value); } // 增長年 function AddYears(date,value) { date.setFullYear(date.getFullYear()+value); } // 是否爲今天 function IsToday(date) { return IsDateEquals(date,new Date()); } // 是否爲當月 function IsThisMonth(date) { return IsMonthEquals(date,new Date()); } // 兩個日期的年是否相等 function IsMonthEquals(date1,date2) { return date1.getMonth()==date2.getMonth()&&date1.getFullYear()==date2.getFullYear(); } // 判斷日期是否相等 function IsDateEquals(date1,date2) { return date1.getDate()==date2.getDate()&&IsMonthEquals(date1,date2); } // 返回某個日期對應的月份的天數 function GetMonthDayCount(date) { switch(date.getMonth()+1) { case 1:case 3:case 5:case 7:case 8:case 10:case 12: return 31; case 4:case 6:case 9:case 11: return 30; } //二月份 date=new Date(date); var lastd=28; date.setDate(29); while(date.getMonth()==1) { lastd++; AddDays(date,1); } return lastd; } // 返回兩位數的年份 function GetHarfYear(date) { var v=date.getYear(); if(v>9)return v.toString(); return "0"+v; } // 返回月份(修正爲兩位數) function GetFullMonth(date) { var v=date.getMonth()+1; if(v>9)return v.toString(); return "0"+v; } // 返回日 (修正爲兩位數) function GetFullDate(date) { var v=date.getDate(); if(v>9)return v.toString(); return "0"+v; } // 替換字符串 function Replace(str,from,to) { return str.split(from).join(to); } // 格式化日期的表示 function FormatDate(date,str) { str=Replace(str,"yyyy",date.getFullYear()); str=Replace(str,"MM",GetFullMonth(date)); str=Replace(str,"dd",GetFullDate(date)); str=Replace(str,"yy",GetHarfYear(date)); str=Replace(str,"M",date.getMonth()+1); str=Replace(str,"d",date.getDate()); return str; }
參考資料: js時間日期處理 http://www.studyofnet.com/news/898.htmlorm