JS中获取时间以及格式化处理
获取时间
var time = new Date();
console.log(time.getYear()); //获取已过年数,2021-1900
console.log(time.getFullYear()); //获取完整的年份,2021
console.log(time.getMonth()); //获取当前月份(0-11,0代表1月)
console.log(time.getDate()); //获取当前日(1-31)
console.log(time.getDay()); //获取当前星期X(0-6,0代表星期天)
console.log(time.getTime()); //获取当前时间(从1970.1.1开始的毫秒数)
console.log(time.getHours()); //获取当前小时数(0-23)
console.log(time.getMinutes()); //获取当前分钟数(0-59)
console.log(time.getSeconds()); //获取当前秒数(0-59)
console.log(time.getMilliseconds()); //获取当前毫秒数(0-999)
console.log(time.toLocaleDateString()); //获取当前日期,2021/12/1
console.log(time.toLocaleTimeString());//获取当前时间
console.log(time.toLocaleString());//获取当前日期和时间
运行结果
格式化日期
格式化的方法,
参数1:格式化格式,例如“yyyy-MM-dd mm:hh:ss”
参数2:日期对象
/**************************************时间格式化处理************************************/
dateFtt(fmt, date) { //author: meizz
var o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"h+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
方法调用
console.log(dateFtt("yyyy-MM-dd hh:mm:ss",time));
console.log(dateFtt("yyyy-MM-dd",time));