js 获取时间基本方法
var time = new Date();
1. time.getYear(); //获取当前年份(2位)
2. time.getFullYear(); //获取完整的年份(4位,1970……)
3. time.getMonth(); //获取当前月份(0-11,0代表1月)
4. time.getDate(); //获取当前日(1-31)
5. time.getDay(); //获取当前星期X(0-6,0代表星期天)
6. time.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
7. time.getHours(); //获取当前小时数(0-23)
8. time.getMinutes(); //获取当前分钟数(0-59)
9. time.getSeconds(); //获取当前秒数(0-59)
10. time.getMilliseconds(); //获取当前毫秒数(0-999)
11. time.toLocaleDateString(); //获取当前日期
12. time.toLocaleTimeString(); //获取当前时间
13. time.toLocaleString(); //获取日期与时间
//时间格式转换
const getFormatTime = (time, format) => {
time = new Date(time);
var timeConfig = {
'M+': time.getMonth() + 1,
'd+': time.getDate(),
'H+': time.getHours(),
'h+': time.getHours(),
'm+': time.getMinutes(),
's+': time.getSeconds()
};
if (/(y+)/.test(format.toLowerCase())) {
format = format.replace(RegExp.$1, (`${time.getFullYear()}`).substr(4 - RegExp.$1.length));
};
for (var i in timeConfig) {
if (new RegExp(`(${i})`).test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? timeConfig[i] : (`00${timeConfig[i]}`).substr((`${timeConfig[i]}`).length))
};
};
return format;
};
本文介绍JavaScript中处理时间的方法,包括获取年、月、日、时、分、秒等信息的具体函数,以及如何进行时间格式化。
1058

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



