关于JS的Date对象的探究
一次代码审核,其中刚好遇见了一些知识点记录顺带整理一下吧
- date对象是javascript语言中内置的数据类型,用于提供日期和时间的操作接口。
- Date类型使用自UTC1970年1月1日0点开始经过的毫秒数来保存日期,它可以表示的时间范围是1970年1月1日0点前后的各1亿天。
概念性的东西请移步这个博主的文章,写的真好!
https://www.cnblogs.com/xiaohuochai/p/5663102.html
https://www.cnblogs.com/xiaohuochai/p/5663102.html
https://www.cnblogs.com/xiaohuochai/p/5663102.html
下面让我们来看一些函数实例
- 每个Object对象都有 toLocaleString/toString/valueOf 这些方法。
- 像其他对象一样,Date继承了Object并重写了这些方法。
由于 Date.valueOf 直接返回的是是日期的毫秒表示,所以我们可以通过
+new Date()
获取
我们我们最好是用 Date.now(ES5新增方法) 而不是 Date.parse
const pre1 = Date.parse(new Date()); // 1517828782000 - 丢失了毫秒的信息
const pre2 = Date.now(new Date()); // 1517828814628
const pre3 = (+ new Date()); // 1517828814628
console.log(pre1, pre2, pre3);
要注意客户端时间和服务端时间的区别(精确的时间还是需要 后端 来做的)
const a = new Date();
这里的 a 最后的值是客户端的时间(注意,不是联网后的当天时间!!!!!!)
我一直蠢蠢地以为这会是 正确的时间。
它将会是本地客户端的时间。意即是说,若我脑残地把自己手机或者电脑时间改了,他就!!!!
关于时间函数的一些深入理解
此版块内容(copy至)源自:想看更多点我
Date对象属性描述(Object这一对象都有的东西)
- constructor:返回创建此对象的Date函数的引用,可用于判断是否是 Date 对象
const test = new Date(); if (test.constructor === Array) { console.log("test is Array"); }; if (test.constructor === Date) { console.log("test is Date"); } // 最后打出 test is Date Object.prototype.toString.call(new Date()) === '[object Date]' // true
- prototype:使我们有能力向对象添加属性和方法
需要注意的是这里不要乱用箭头函数哦。箭头函数的this。Date.prototype.show = function() { console.log(this); } const a = new Date(); a.show();
Date对象的常用方法摘抄
const now = new Date()
- getYear 注:ES3 之后此方法已经被 弃用
- getDay 获取当前星期X (0-6, 0 代表星期天)
- getFullYear 获取当前年份(4位, 1970-????)
- getMonth 获取当前月份(0-11,0 代表1月)
- getDate 获取当前日(1-31)
- getHours 获取当前小时数(0-23)
- getMinutes 获取当前分钟数(0-59)
- getSeconds 获取当前秒数(0-59)
const a = new Date();
const o = (date) => {
return {
"noYear": date.getYear(), // 118
"year": date.getFullYear(), // 2018
"month": date.getMonth(), // 0(1月)
"date": date.getDate(), // 31
"hour": date.getHours(), // 20
"minutes": date.getMinutes(), // 18
"seconds": date.getSeconds() // 9
}
}
console.log(o(a));
关于一些时间的应用场景
- 1.判断闰年
const isLeapYear = (...needles) => {
for (const obj of needles) {
if ((obj % 4 === 0 && obj % 100 !==0) || obj % 400 === 0) {
console.log(obj + "是闰年");
continue;
}
console.log(obj + "不是闰年");
}
}
isLeapYear(2004, 2000, 500);
complete.
一遍一遍的咀嚼,总会烂的。