Date日期对象
创建日期对象:
- 默认是当前时间;
var date=new Date();
- 获取指定时间日期的date对象(兼容性最强)—推荐
var date=new Date("2020-05-12 14:25:16");
var date2=new Date("2017/01/27 12:00:00");
- 根据时间标准格式获取日期对象(了解)
var date=new Date("Sun May 12 2019 14:25:16 GMT+0800 (中国标准时间)");
- 根据年月日多个参数获取日期
var date=new Date(2018,8,12,16,23,12);
分别获取年月日小时分秒的方法:
- 获取日 1-31
getDate()
- 获取星期 0-6(0代表周日)
getDay()
- 获取月 0-11(1月从0开始)
getMonth()
- 获取完整年份(浏览器都支持)
getFullYear()
- 获取小时 0-23
getHours()
- 获取分钟 0-59
getMinutes()
- 获取秒 0-59
getSeconds()
- 获取毫秒(1s = 1000ms)
getMilliseconds()
- 返回累计毫秒数(从1970/1/1午夜)
getTime()
var date=new Date();
console.log(date);
//Wed Jul 08 2020 21:18:57 GMT+0800 (中国标准时间)
获取指定日期的date对象
var date=new Date("2020-05-12 14:25:16");
console.log(date);
//Tue May 12 2020 14:25:16 GMT+0800 (中国标准时间)
var date=new Date("Sun May 12 2019 14:25:16 GMT+0800 (中国标准时间)");
console.log(date);
//Sun May 12 2019 14:25:16 GMT+0800 (中国标准时间)
var date=new Date(2018,8,12,16,23,12);
console.log(date);
//Wed Sep 12 2018 16:23:12 GMT+0800 (中国标准时间)
var date1=new Date("2018","08",12,16,23,12);
console.log(date1);
//Wed Sep 12 2018 16:23:12 GMT+0800 (中国标准时间)
var date1=new Date();
var date=new Date("2020-7-8 21:35:02");
console.log(date);//Wed Jul 08 2020 21:27:30 GMT+0800 (中国标准时间)
// 日期
console.log(date.getDate());//8
// 星期 从周日算一周的第一天 所以从0开始
console.log(date.getDay ());//3
// 月 从0开始 所以要+1
console.log(date.getMonth());//6
// 四位的年份
console.log(date.getFullYear());//2020
// 时 24小时制
console.log(date.getHours());//21
// 分
console.log(date.getMinutes());//35
// 秒
console.log(date.getSeconds());//02
//零多少毫秒(1秒=1000毫秒 此处是不足一秒部分)
console.log(date.getMilliseconds());//718
//距离1970年 00:00:00 到现在所有的毫秒值
console.log(date.getTime());//1594215302781
系统自带的构造函数
var d=new Date();
function Date(){
//系统自带的构造函数
}
获取毫秒值的四个方法:
var d=new Date();
var date1=Date.now();//构造函数名直接调用的静态方法(后面讲)
var date2= +new Date();
var date3=new Date().getTime(); //推荐使用的
var date4= d.valueOf();
console.log(date1);//1594215764523
console.log(date2);//1594215764523
console.log(date3);//1594215764523
console.log(date4);//1594215764523
日期转换
var date=new Date("2018-05-27 16:12:25");
Date.parse("2018-05-27 16:12:25");
从日期格式的字符串中解析出距离1970年的毫秒值;
new Date(距离1970年的毫秒值)返回一个解析毫秒值后的date对象;
如果字符串不是标准的日期格式,那么解析返回NaN;
几秒以后
setTimeout
//在栈内存中创建per,在堆内存开辟空间
var per=new Person();
//匿名对象:只有堆内存,没有栈内存,只能用一次
new Person();