js获取当前日期(年份,月份,时间),实现方法:
function getDateTime (type) {
var date = new Date();
var hengGang = "-";
var maoHao = ":";
var year = date.getFullYear();
var month = date.getMonth() + 1;
var curDate = date.getDate();
var curHours = date.getHours();
var curMinutes = date.getMinutes();
var curSeconds = date.getSeconds();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (curDate >= 0 && curDate <= 9) {
curDate = "0" + curDate;
}
if (curHours >= 0 && curHours <= 9) {
curHours = "0" + curHours;
}
if (curMinutes >= 0 && curMinutes <= 9) {
curMinutes = "0" + curMinutes;
}
if (curSeconds >= 0 && curSeconds <= 9) {
curSeconds = "0" + curSeconds;
}
var currentdate = "";
if (type == "year") {
currentdate = year;
return currentdate;
} else if (type == "month") {
currentdate = year + hengGang + month;
return currentdate;
} else {
currentdate = year + hengGang + month + hengGang + curDate + " " + curHours + maoHao + curMinutes + maoHao + curSeconds;
return currentdate;
}
}
var year = getDateTime('year');
console.log(year); // 2021
var month = getDateTime('month');
console.log(month); // 2021-12
var date = getDateTime('');
console.log(date); // 2021-12-03 09:00:00
本文详细介绍了如何使用JavaScript获取当前日期,包括年份、月份、日期、小时、分钟和秒,并提供了示例代码。适合初学者理解日期对象的使用。
&spm=1001.2101.3001.5002&articleId=121690944&d=1&t=3&u=ec9b1f7673ee4d70b524d073e98f2a7b)
409

被折叠的 条评论
为什么被折叠?



