獲取當前時間及時間戳

1.獲取系統當前時間

var?myDate =?new?Date();//獲取系統當前時間

2.獲取特定格式的時間

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( ); //獲取日期與時間

3.獲取當前時間戳

(1)var timestamp =Date.parse(new Date());

from W3C的javascript

注:得到的結果:1280977330000 注意:這里得到的結果將后三位(毫秒)轉換成了000顯示,使用時可能會出現問題。例如動態添加頁面元素id的時候,不建議使用。

(2)vartimestamp =(newDate()).valueOf();

結果:1280977330748

(3)vartimestamp=newDate().getTime();

結果:1280977330748

注:

? ? ?js中單獨調用new Date(),例如document.write(new Date());顯示的結果是:Mar 31 10:10:43 UTC+0800 2012 這種格式的時間

? ? ?但是用new Date() 參與計算會自動轉換為從1970.1.1開始的毫秒數。

總結: js 獲取當前年月日時分秒星期

$("#aa").click(function () {

var date = new Date();

this.year = date.getFullYear();

this.month = date.getMonth() + 1;

this.date = date.getDate();

this.day = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")[date.getDay()];

this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();

this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();

this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

var currentTime = "現在是:" + this.year + "年" + this.month + "月" + this.date + "日 " + this.hour + ":" + this.minute + ":" + this.second + " " + this.day;

alert(currentTime);

});

W3C的Date具體講解:? ? http://www.w3school.com.cn/jsref/jsref_obj_date.asp

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容