在JavaScript中获取当前时间的年月日,可以使用内置的Date
对象。以下是几种常见的方法:
getFullYear()
, getMonth()
, getDate()
方法const now = new Date();
const year = now.getFullYear(); // 获取年份
const month = now.getMonth() + 1; // 获取月份(注意:月份从0开始,所以需要加1)
const day = now.getDate(); // 获取日期
console.log(`当前时间是:${year}年${month}月${day}日`);
toLocaleDateString()
方法const now = new Date();
const dateString = now.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
console.log(`当前时间是:${dateString}`);
Date
对象的方法const now = new Date();
const formattedDate = `${now.getFullYear()}年${String(now.getMonth() + 1).padStart(2, '0')}月${String(now.getDate()).padStart(2, '0')}日`;
console.log(`当前时间是:${formattedDate}`);
Date
对象:JavaScript中的Date
对象用于处理日期和时间。getFullYear()
:返回四位数的年份。getMonth()
:返回月份(0-11),所以需要加1才能得到正确的月份。getDate()
:返回月份中的日期(1-31)。toLocaleDateString()
:根据本地时间格式返回日期字符串,可以指定语言和选项。padStart()
:用于在字符串前填充字符,确保月份和日期都是两位数。通过这些方法,你可以轻松地在JavaScript中获取并格式化当前时间的年月日。
Hello Serverless 来了
云+社区技术沙龙[第10期]
“中小企业”在线学堂
腾讯云GAME-TECH沙龙
云+社区技术沙龙[第5期]
第四期Techo TVP开发者峰会
腾讯云GAME-TECH游戏开发者技术沙龙
云+社区技术沙龙[第28期]
serverless days
领取专属 10元无门槛券
手把手带您无忧上云