Date()方法的使用
如果Date()不写参数,就返回当前时间
如果Date()里面写参数,就返回括号里面输入的时间
1.日期格式化
const date=new Date("1999-2-22 11:11:18");
console.log(date);
console.log(date.getFullYear());
console.log(date.getMonth()+1); //0-11月
console.log(date.getDate()); //??date.getDay()返回星期几?date.getDate()返回第几天
console.log(date.getHours());
console.log(date.getMinutes());
console.log(date.getSeconds());
\
function dateFormat(date,format="YYYY-MM-DD HH:mm:ss"){
const config={
YYYY:date.getFullYear(),
MM:date.getMinutes()+1,
DD:date.getDate(),
HH:date.getHours(),
mm:date.getMinutes(),
ss:date.getSeconds()
\
};
for (const key in config){
format=format.replace(key,config[key]); //每当key被找到,都会被config[key]替换
}
return format;
}
console.log(dateFormat(date,"YYYY年MM月DD日 HH:mm:ss"));
2.日期时间戳
const date=new Date();
console.log(date);
console.log(typeof date);
console.log(date*1);//时间戳
\
const hd=Date();
console.log(hd);
console.log(typeof hd);
console.log(hd*1);
\
const date1=Date.now();
console.log(date1);
const start=Date.now();
for(let i=0;i<200000000;i++){}
const end=Date.now();
console.log((end-start)/1000+"秒");
\
\
\
console.time("for");
for(let i=0;i<200000000;i++){}
console.timeEnd("for");
\
const date2=new Date("1999-9-22 3:22:18");
console.log(date2);
console.log(date2.getMonth()+1);
\
let date3 =new Date(1999,2,22,13,22,19);
console.log(date3);
\
\
let array =[1998,2,22,13,22,19];
let date4=new Date(...array);//展开数组
console.log(date4);
3.获取日期的总的毫秒形式
Date 对象是基于1970年1月1日(世界标准时间)起的毫秒数
// 实例化Date对象
var now = new Date();
// 1. 用于获取对象的原始值
console.log(date.valueOf())
console.log(date.getTime())
// 2. 简单写可以这么做
var now = +new Date();
// 3. HTML5中提供的方法,有兼容性问题
var now = Date.now()
4.输出指定日期
const date2 = new Date("2019-8-8");
console.log(date2);
const month = date2.getMonth() + 1;
const year = date2.getFullYear();
const day = date2.getDate();
const week = date2.getDay();
\
const arry = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
console.log(year + '年' + month + '月' + day + '日' + arry[week]);