目录
一、Date对象详解
1.Date对象
Date 对象用于处理日期与时间。
2.创建Date对象
let date = new Date();
3.Date对象属性
属性 | 描述 |
constuctor | 返回对创建此对象的Date函数的引用 |
prototype | 使您有能力向对象添加属性和方法 |
4.Date对象方法
(1)getDate() 返回一个月中的某一天(1-31)
let date = new Date();
console.log(date.getDate());
(2)getDay() 返回一周中的某一天(0-6)
let date = new Date();
console.log(date.getDay());
(3)getFullYear() 返回年份
let date = new Date();
console.log(date.getFullYear());
(4)getHours() 返回Date对象的小时(0-23)
let date = new Date();
console.log(date.getHours());
(5)getMillseconds() 返回Date对象的毫秒数(0-999)
let date = new Date();
console.log(date.getMilliseconds());
(6)getMinutes() 返回Date对象的月份(0-11)因为月份返回0-11,因此一般获取月份都要 + 1
let date = new Date();
console.log(date.getMonth());
(7)getSeconds() 返回Date对象的秒数(0-59)
let date = new Date();
console.log(date.getSeconds());
(8)getTime() 返回1970年1月一日至今的毫秒数,即时间戳
let date = new Date();
console.log(date.getTime());
这些就是我们经常使用的Date对象的方法,其他方法可参考菜鸟教程
5.Date对象的应用(节流函数时间戳写法)
Date.now() 相当于 date.getTIme() 获取时间戳
function throttled(fn, delay) {
let oldTime = Date.now();
return function (...args) {
let newTIme = Date.now();
if (newTIme - oldTime >= delay) {
fn.apply(this, args);
oldTime = Date.now();
}
};
}
二、时间戳和时间的相互转换
1.时间转换为时间戳
// Date.parse()不推荐这种写法,毫秒级别的数值直接被转化为000
let date1 = Date.parse(new Date());
// valueOf()函数返回指定对象的原始值获得准确的时间数值
let date2 = new Date().valueOf();
// getTime()通过原型方法直接获得当前时间的毫秒数
let date3 = new Date().getTime();
// Number() 将时间转化为一个number类型的数值
let date4 = Number(new Date());
console.log(date1);
console.log(date2);
console.log(date3);
console.log(date4);
打印结果如下
2.时间戳转换为时间
(1)自己手写转换函数利用 Date对象的方法
// 时间戳转换成时间格式
var formatDate = function (date) {
// 如果传入的时间戳为10位需*1000,时间戳为13位的话不需乘1000
date = new Date(date);
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
var h = date.getHours();
var m1 = date.getMinutes();
var s = date.getSeconds();
// 过滤格式
m = m < 10 ? '0' + m : m;
d = d < 10 ? '0' + d : d;
h = h < 10 ? '0' + h : h;
m1 = m1 < 10 ? '0' + m1 : m1;
s = s < 10 ? '0' + s : s;
// 拼接时间格式
return y + '-' + m + '-' + d + ' ' + h + ':' + m1 + ':' + s;
};
console.log(formatDate(1685671570448));
另一种写法,可以根据 now.toTimeString().substr(0, 8) 获取后面的时分秒格式,更加简便
// 时间戳转换成时间格式
var formatDate = function (date) {
// 如果传入的时间戳为10位需*1000,时间戳为13位的话不需乘1000
date = new Date(date);
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
// 过滤格式
m = m < 10 ? '0' + m : m;
d = d < 10 ? '0' + d : d;
return y + '-' + m + '-' + d + ' ' + date.toTimeString().substr(0, 8);
};
console.log(formatDate(1685671570448));
输出结果如下
(2)可以使用replace方法进行转置
function getLocalTime(nS) {
// parseInt可解析一个字符串,并返回一个整数
// toLocalString()方法可根据本地时间把date对象转换为字符串,并返回结果
// replace利用正则进行匹配替换
return new Date(parseInt(nS)).toLocaleString().replace(/:\d{1,2}$/, ' ');
}
console.log(getLocalTime(1685671570448));
输出结果如下
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/148353.html