获取日期/时间/星期
Posted web半晨
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取日期/时间/星期相关的知识,希望对你有一定的参考价值。
1、介绍
1 获取年
2 获取月
3 获取日
4 获取年月日
5 获取时
6 获取分
7 获取秒
8 获取时分秒
9 获取星期
10 获取年月日时分秒(yy-MM-dd hh:MM:ss)
不传默认返回 yy-MM-dd hh:MM:ss
2、代码
function getDateTimeWeek(key = 10) {
key = Number(key);
let dateTime = new Date(),
year = dateTime.getFullYear(),
month = dateTime.getMonth() + 1,
day = dateTime.getDate(),
hour = dateTime.getHours(),
minute = dateTime.getMinutes(),
second = dateTime.getSeconds(),
weeks = dateTime.getDay();
month = month < 10 ? "0" + month : month;
day = day < 10 ? "0" + day : day;
hour = hour < 10 ? "0" + hour : hour;
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
let result = null;
switch (key) {
case 1:
result = `${year}`;
break;
case 2:
result = `${month}`;
break;
case 3:
result = `${day}`;
break;
case 4:
result = `${year}-${month}-${day}`;
break;
case 5:
result = `${hour}`;
break;
case 6:
result = `${minute}`;
break;
case 7:
result = `${second}`;
break;
case 8:
result = `${hour}:${minute}:${second}`;
break;
case 9:
result = `${weeks}`;
break;
case 10:
result = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
break;
default:
console.log("出错啦!");
break;
};
return result;
};
console.log(getDateTimeWeek(10));
console.log(getDateTimeWeek());
3、演示
以上是关于获取日期/时间/星期的主要内容,如果未能解决你的问题,请参考以下文章