在JavaScript中,可以通過以下步驟獲取系統(tǒng)當(dāng)前時(shí)間:
1.創(chuàng)建一個(gè)Date對(duì)象,即通過調(diào)用Date()函數(shù)創(chuàng)建一個(gè)Date實(shí)例,代碼如下:
var now = new Date();
2.通過日期
var year = now.getFullYear(); //獲取完整的年份(4位,1970-????)
var month = now.getMonth() + 1; //獲取當(dāng)前月份(0-11,0代表1月)
var day = now.getDate(); //獲取當(dāng)前日(1-31)
var hour = now.getHours(); //獲取當(dāng)前小時(shí)數(shù)(0-23)
var minute = now.getMinutes(); //獲取當(dāng)前分鐘數(shù)(0-59)
var second = now.getSeconds(); //獲取當(dāng)前秒數(shù)(0-59)
var millisecond = now.getMilliseconds(); //獲取當(dāng)前毫秒數(shù)(0-999)
var weekDay = now.getDay(); //獲取當(dāng)前星期X(0-6,0代表星期天)
3.根據(jù)需求對(duì)獲取到的時(shí)間信息進(jìn)行格式化,如將日期和時(shí)間拼接成指定的格式。例如,獲取當(dāng)前時(shí)間的年月日和時(shí)分秒,格式為“yyyy-MM-dd hh:mm:ss”,代碼如下:
var now = new Date();
var year = now.getFullYear(); //獲取完整的年份(4位,1970-????)
var month = now.getMonth() + 1; //獲取當(dāng)前月份(0-11,0代表1月)
var day = now.getDate(); //獲取當(dāng)前日(1-31)
var hour = now.getHours(); //獲取當(dāng)前小時(shí)數(shù)(0-23)
var minute = now.getMinutes(); //獲取當(dāng)前分鐘數(shù)(0-59)
var second = now.getSeconds(); //獲取當(dāng)前秒數(shù)(0-59)
var time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
通過以上步驟,即可獲取系統(tǒng)當(dāng)前時(shí)間,并對(duì)其進(jìn)行格式化和處理。