一、Data對象的常用方法
const myDate = new Date();
myDate.getYear(); //獲取當(dāng)前年份(2位)
myDate.getFullYear(); //獲取完整的年份(4位,1970-????)
myDate.getMonth(); //獲取當(dāng)前月份(0-11,0代表1月)
myDate.getDate(); //獲取當(dāng)前日(1-31)
myDate.getDay(); //獲取當(dāng)前星期X(0-6,0代表星期天)
myDate.getTime(); //獲取當(dāng)前時(shí)間(從1970.1.1開始的毫秒數(shù))
myDate.getHours(); //獲取當(dāng)前小時(shí)數(shù)(0-23)
myDate.getMinutes(); //獲取當(dāng)前分鐘數(shù)(0-59)
myDate.getSeconds(); //獲取當(dāng)前秒數(shù)(0-59)
myDate.getMilliseconds(); //獲取當(dāng)前毫秒數(shù)(0-999)
myDate.toLocaleDateString(); //獲取當(dāng)前日期
myDate.toLocaleTimeString(); //獲取當(dāng)前時(shí)間
myDate.toLocaleString( ); //獲取日期與時(shí)間
//toLocaleString( )方法默認(rèn)輸出格式為 '2023/4/1 22:22:18'
二、格式化輸出
(1)逐個(gè)提取并拼接字符串
function printDate() {
const d = new Date();
const year = d.getFullYear();
const month = d.getMonth() > 8 ? d.getMonth() + 1 : "0" + (d.getMonth() + 1);
const date = d.getDate() > 9 ? d.getDate() : "0" + d.getDate();
const hours = d.getHours() > 9 ? d.getHours() : "0" + d.getHours();
const minutes = d.getMinutes() > 9 ? d.getMinutes() : "0" + d.getMinutes();
const seconds = d.getSeconds() > 9 ? d.getSeconds() : "0" + d.getSeconds();
return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
}
(2)一步到位提取年月日時(shí)分秒(重點(diǎn))
首先,提取數(shù)據(jù)到數(shù)據(jù)
function extract(){
const d = new Date(new Date().getTime() + 8*3600*1000);
return new Date(d).toISOString().split(/[^0-9]/).slice(0,-2);
}
然后,拼接數(shù)據(jù)格式化輸出文章來源:http://www.zghlxwxcb.cn/news/detail-774931.html
function forTime(){
const d = new Date(new Date().getTime() + 8*3600*1000);
const dList = d.toISOString().split(/[^0-9]/).slice(0,-2);
return `${dList[0]}年${dList[1]}月${dList[2]}日 ${dList[3]}時(shí)${dList[4]}分${dList[5]}秒`
}
(附上,過程剖析)文章來源地址http://www.zghlxwxcb.cn/news/detail-774931.html
到了這里,關(guān)于關(guān)于使用JS獲取當(dāng)前時(shí)間并格式化輸出的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!