1.var cDate = new Date(); console.log(cDate);
输出:ri May 07 2021 15:00:45 GMT+0800 (中国标准时间)
2.常用方法
<script>
var cDate = new Date();
console.log(cDate);
//Fri May 07 2021 15:17:25 GMT+0800 (中国标准时间)
console.log(cDate.getTime());
//1620371845943 返回毫秒数
console.log(cDate.getMilliseconds());
//943 ?
console.log(cDate.getSeconds());
//25
console.log(cDate.getMinutes());
//17
console.log(cDate.getHours());
//15
console.log(cDate.getDay());
//5 返回星期,0周日 6周六
console.log(cDate.getDate());
//7 返回当前月的第几天
console.log(cDate.getMonth());
//4 返回月份,从0开始
console.log(cDate.getFullYear());
//2021
</script>
3.写一个函数,格式化日期对象:返回YYYY-MM-dd hh:mm:ss
。
<script>
var c = formatDate(new Date());
console.log(c);
function formatDate(d) {
/**
* @Description: 格式化函数
* @author Tsukiis Chen
* @date 2021/5/7
* @param {Date}date
*/
//验证
if (!d instanceof Date) {
return;
}
// 转化
var year = d.getFullYear();
var mouth = d.getMonth() + 1;
var day = d.getDate();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
/*转换格式*/
mouth = mouth < 10 ? '0' + mouth : mouth;
day = day < 10 ? '0' + day : day;
hour = hour < 10 ? '0' + hour : hour;
minute = minute < 10 ? '0' + minute : minute;
second = second < 10 ? '0' + second : second;
return year + '-' + mouth + '-' + day + ' ' + hour + ':' + minute + ':'+second;
}
</script>