/* new Date() 获取当前时间 */
/* get方法 */
let myDate = new Date(); //Thu Jun 09 2022 13:28:02 GMT+0800 (中国标准时间)
/* getFullYear() 获取当前时间年份 */
myDate.getFullYear() // 2022
/* getMonth() 获取当前时间月份 0-11 0相当于1月 11月相当于12月 */
myDate.getMonth() // 5 实际月份需要加 1
myDate.getMonth() + 1 // 6
/* getDate() 获取当前日 */
myDate.getDate() // 9
// 通过上面函数可得出年月日
let srt = `${myDate.getFullYear()}年 - ${myDate.getMonth() + 1}月 - ${myDate.getDate()}日` // 当前年月日 2022年 - 6月 -9日
/* getDay() 获取当前星期几 0-6 0相当于星期天 */
myDate.getDay() // 4
/* getHours() 获取当前小时 24小时 */
myDate.getHours()
/* getMinutes() 获取当前分钟 60分钟 */
myDate.getMinutes()
/* getSeconds() 获取当前秒 60秒 */
myDate.getSeconds()
/* getTime() 获取当前时间距离1970-01-01所用的毫秒数 */
myDate.getTime() // 1654756083717 new Date() 涉及类型转换
Date.now() // 1654756083717 性能更加也是获取毫秒数
// 获取格式化后的 年-月-日 时:分:秒
function getTime() {
let DataTime = new Date();
let year = DataTime.getFullYear(), // 年
month = DataTime.getMonth() + 1, // 月
day = DataTime.getDate(), // 日
hours = DataTime.getHours(), // 小时
minutes = DataTime.getMinutes(), // 分钟
seconds = DataTime.getSeconds(); // 秒
return `${year}-${month<10?'0'+month:month}-${day<10?'0'+day:day} ${hours<10?'0'+hours:hours}:${minutes<10?'0'+minutes:minutes}:${seconds<10?'0'+seconds:seconds}`
}
getTime(); // 2022-06-09 14:24:04
/* getMilliseconds 获取日期中的毫秒数 0-999*/
myDate.getMilliseconds()
/* toLocaleDateString() 获取当前日期 */
myDate.toLocaleDateString(); // 2022/6/9
/* toLocaleTimeString() 获取当前时间 */
myDate.toLocaleTimeString(); // 14:24:04
/* toLocaleString() 获取当前日期和时间 */
myDate.toLocaleString(); // 2022/6/9 14:24:04
/* set 方法 */
/* setFullYear() 设置年份2007 */
myDate.setFullYear("2007"); // 2007/6/9 14:40:51
/* setMonth() 设置月份 最小为0 最大为11*/
myDate.setMonth('11') // 2007/12/9 14:49:13
/* setDate() 设置日 当前月的最大日期如果超过则月份 + 1 */
myDate.setDate('1') // 2007/12/1 14:50:39