js獲取當(dāng)前年月日詳細(xì)教程(看這一篇就夠了)
js獲取當(dāng)前年月日
// 獲取當(dāng)前時(shí)間
const today = new Date();
// 獲取當(dāng)前時(shí)間(today)的年份
const year = today.getFullYear();
// 獲取月份
const month = String(today.getMonth() + 1).padStart(2, '0');
// 獲取當(dāng)前日
const day = String(today.getDate()).padStart(2, '0');
// 得到年月日
const thisDayDate = `${year}-${month}-${day}`; //打印當(dāng)前日期1. 當(dāng)前日期
1.1 const today = new Date();
函數(shù)new Date() 為獲取當(dāng)前時(shí)間

2. 當(dāng)前日期的年份
2.1. const year = today.getFullYear();
函數(shù) getFullYear() 為獲取當(dāng)前時(shí)間today的年份
3. 當(dāng)前日期的月份
const month = String(today.getMonth() + 1).padStart(2, '0');
3.1 getMonth()返回的月份是從0開始計(jì)數(shù),十二個(gè)月份打印出來也就是0-11;
3.2 today.getMonth() + 1 假如當(dāng)前月份是11月,那么不加一打印出來就是10,加1才能顯示正確月份。就比如數(shù)組的索引也是從0開始計(jì)數(shù)。
3.3 當(dāng)前是2023年11月,下面打印today.getMonth()d的運(yùn)行結(jié)果為10;

3.4 當(dāng)前是2023年11月,下面打印today.getMonth() + 1的運(yùn)行結(jié)果為11;

3.5 String(today.getMonth() + 1)
可以看到打印的10或者11字體都是藍(lán)色的,那么就代表當(dāng)前的month為number類型;
將得到的月份用String轉(zhuǎn)換為字符串String類型;
下面轉(zhuǎn)換之后查看字體為黑色,就代表當(dāng)前為String類型;

3.6 padStart方法來確保月份始終以兩位數(shù)字表示,不足兩位的前面添加0
4. 獲取當(dāng)前日
const day = String(today.getDate()).padStart(2, '0');
4.1 today.getDate() 獲取當(dāng)前日期(月中的哪一天);
4.2 String將其轉(zhuǎn)換為字符串;
4.3 使用padStart方法來確保日期始終以兩位數(shù)字表示,不足兩位的前面添加0,今天是7號(hào),所以打印出來是07
5. 當(dāng)前年月日
const thisDayDate = `${year}-${month}-${day}`; //打印當(dāng)前日期
5.1 模板字符串${}拼接 年-月-日

附:獲取當(dāng)前年月日星期時(shí)分秒
//獲取當(dāng)前日期函數(shù)
function getNowFormatDate() {
let date = new Date(),
obj = {
year: date.getFullYear(), //獲取完整的年份(4位)
month: date.getMonth() + 1, //獲取當(dāng)前月份(0-11,0代表1月)
strDate: date.getDate(), // 獲取當(dāng)前日(1-31)
week: '星期' + '日一二三四五六'.charAt(date.getDay()), //獲取當(dāng)前星期幾(0 ~ 6,0代表星期天)
hour: date.getHours(), //獲取當(dāng)前小時(shí)(0 ~ 23)
minute: date.getMinutes(), //獲取當(dāng)前分鐘(0 ~ 59)
second: date.getSeconds() //獲取當(dāng)前秒數(shù)(0 ~ 59)
}
Object.keys(obj).forEach(key => {
if (obj[key] < 10) obj[key] = `0${obj[key]}`
// console.log(obj[key])
})
return `${obj.year}年${obj.month}月${obj.strDate}日${obj.week} ${obj.hour}:${obj.minute}:${obj.second}`
}總結(jié)
到此這篇關(guān)于js獲取當(dāng)前年月日的文章就介紹到這了,更多相關(guān)js獲取當(dāng)前年月日內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript跟隨鼠標(biāo)x,y坐標(biāo)移動(dòng)的字效果
javascript跟隨鼠標(biāo)x,y坐標(biāo)移動(dòng)的字效果...2007-04-04
對(duì)javascript的一點(diǎn)點(diǎn)認(rèn)識(shí)總結(jié)《javascript高級(jí)程序設(shè)計(jì)》讀書筆記
Javascript專為與網(wǎng)頁(yè)交互而設(shè)計(jì)的腳本語(yǔ)言,由下列三個(gè)部門構(gòu)造2011-11-11
JavaScript語(yǔ)法約定和程序調(diào)試原理解析
利用element-ui實(shí)現(xiàn)遠(yuǎn)程搜索兩種實(shí)現(xiàn)方式
js實(shí)現(xiàn)一個(gè)鏈接打開兩個(gè)鏈接地址的方法

