時間對像是一個我們經常要用到的對象,無論是做時間輸出、時間判斷等操作時都與這個對象離不開。除開JavaScript中的時間對像外,在VbScript中也有許多的時間對象,而且非常好用。下面還是按照我們的流程來進行講解JavaScript中日期函數。
new Date()
new Date(milliseconds)
new Date(datestring)
new Date(year, month)
new Date(year, month, day)
new Date(year, month, day, hours)
new Date(year, month, day, hours, minutes)
new Date(year, month, day, hours, minutes, seconds)
new Date(year, month, day, hours, minutes, seconds, microseconds)
下面對
1.new Date(),沒有參數的時候,創建的是當前時間日期對象。
2.new Date(milliseconds),當參數為數字的時候,那麼這個參數就是時間戳,被視為毫秒,創建一個距離1970年1月一日指定毫秒的時間日期對象。
3.new Date(datestring),此參數是一個字符串,並且此字符串一定能夠使用Date.parse()轉換。
4.以下六個構造函數是精確定義:
1).year,是一個整數,如果是0-99,那麼在此基礎上加1900,其他的都原樣返回。
2).month,是一個整數,範圍是0-11。
3).day,是一個整數,範圍是1-31。
4).hours,是一個整數,範圍是0-23。
5).minutes,是一個整數,範圍是0-59。
6).seconds,是一個整數,範圍是0-59。
7).microseconds 是一個整數,範圍是0-9999。
<html><head><title>時間戳轉化為年月日時分秒</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head><body></body></html><script>window.onload=function(){var now=new Date();//當前系統時間var shijianchuo = now.getTime();//獲取當前時間戳alert("時間戳:"+shijianchuo);var nowdate = new Date(shijianchuo);//將時間戳轉化為日期對象var nowtime=nowdate.Format("yyyy-MM-dd hh:mm:ss");//格式化當前系統時間,相當於將時間戳轉化為年月日時分秒了alert("當前時間:"+nowtime);}/*日期格式化:對Date的擴展,將Date 轉化為指定格式的String年(y)可以用1-4個佔位符,季度(q)可以用1-2個佔位符.月(M)、日(d)、小時(h)、分(m)、秒(s)可以用1-2個佔位符.毫秒(S)只能用1個佔位符(是1-3位的數字) 例子: (new Date()).Format("yyyy-MM-dd hh:mm:ss.S")(new Date()).Format("yyyy-MM-dd hh:mm:ss.S毫秒第qq季度")*/Date.prototype.Format = function (fmt) { var o = {"M+": this.getMonth() + 1, //月"d+": this.getDate(), //日"h+": this.getHours(), //時"m+": this.getMinutes(), //分"s+": this.getSeconds(), //秒"q+": Math.floor((this.getMonth() + 3) / 3), //季度"S": this.getMilliseconds() //毫秒};if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));for (var k in o)if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));return fmt;}</script>