B45. 日期对象 常用库
5.1. 时间戳
在 Python 中我们用
time.time()
获取时间戳,JavaScript 也有类似功能!时间戳就像"电子计时器",记录从1970年1月1日至今的毫秒数,是计算时间差的秘密武器。
5.1.1. 获取时间戳
javascript
// 方法1:直接获取
const timestamp1 = Date.now();
// 方法2:通过Date对象
const timestamp2 = new Date().getTime();
// 方法3:valueOf()方法
const timestamp3 = new Date().valueOf();
易错点 时间戳单位是毫秒!如果要转换为秒,记得除以1000:Math.floor(Date.now() / 1000)
5.2. Date 对象的创建方法
想显示当前日期?试试
new Date()
!就像 Python 的datetime.datetime.now()
,但 JavaScript 的日期处理有点"怪脾气",比如月份从0开始算...
5.2.1. 四种创建方式
javascript
// 当前时间
const now = new Date();
// 时间戳创建
const date1 = new Date(1717027200000); // 2024-05-30
// 日期字符串
const date2 = new Date("2024-05-30T08:00:00");
// 分参数创建(注意月份从0开始!)
const date3 = new Date(2024, 4, 30); // 2024年5月30日
易错点
- 月份参数是0-11!输入5实际代表6月,用
date.getMonth()+1
才能获得真实月份 - 日期字符串解析受浏览器影响(推荐使用
new Date(year, month, day)
保证兼容性)
5.3. Date 对象的格式化提供可读的日期时间
new Date()
直接输出会得到类似Thu May 30 2024 08:00:00
的字符串,想自定义显示格式怎么办?需要手动拼接!
5.3.1. 常用方法
javascript
const date = new Date();
// 获取年月日
const year = date.getFullYear();
const month = date.getMonth() + 1; // 记得+1!
const day = date.getDate();
// 获取时分秒
const hours = date.getHours();
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
console.log(`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
易错点
getMonth()
返回0-11,getDate()
才是获取日期!不要混淆getDate()
和getDay()
(后者是星期几)padStart(2, '0')
可保证个位数补零,避免8:3:5
这样的错误格式
5.4. dayjs 提供日期处理工具
手动拼接日期太麻烦?
dayjs
就像 JavaScript 的"瑞士军刀",让日期操作变得优雅又高效!
5.4.1. 安装与基本用法
在 HTML 中引入:
html
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
javascript
// 解析日期
const today = dayjs(); // 当前时间
const birthday = dayjs("2000-01-01");
// 格式化输出
const formatted = today.format("YYYY-MM-DD HH:mm:ss");
console.log(formatted); // 2024-05-30 14:30:45
5.4.2. 常见操作
功能 | 代码示例 | 说明 |
---|---|---|
时间差 | dayjs().diff(birthday, 'year') | 计算相差多少年 |
加减时间 | today.add(7, 'day').format() | 添加7天后的时间 |
时区支持 | dayjs().tz("Asia/Shanghai").format() | 需配合 dayjs/plugin/timezone 插件 |
易错点
dayjs
是不可变对象!每次操作都会返回新实例- 插件需单独引入(如相对时间插件
relativeTime
)
5.5. lodash 和 es-toolkit 提供常见工具库
开发中常需要去重、分组、延迟执行等功能?
lodash
和es-toolkit
是 JavaScript 的"工具百宝箱"!
5.5.1. 常用工具函数
javascript
// 去重
const unique = _.uniq([1, 2, 2, 3]); // [1, 2, 3]
// 延迟执行
_.delay(() => {
console.log("3秒后执行");
}, 3000);
// 节流函数(防止高频触发)
const throttled = _.throttle(fetchData, 1000);
es-toolkit 特点
- 更轻量级的现代替代方案
- 支持 Tree Shaking
- 示例:javascript
import { debounce } from "es-toolkit"; const debounced = debounce(fetchData, 500);
5.5.2. 与日期结合的场景
javascript
// 处理日期数组
const dates = [new Date(2024, 4, 28), new Date(2024, 4, 30)];
const sorted = _.orderBy(dates, [d => d.getTime()], ['asc']);
这一节的更多内容,建议查询两库的官方文档。
知识回顾
- 时间戳单位是毫秒,
Date.now()
快速获取 - 创建日期时月份从0开始,格式化需手动拼接
dayjs
简化日期操作,支持插件扩展lodash
/es-toolkit
提供实用工具函数- 注意浏览器兼容性和数据类型转换
课后练习
基础题
(选择)获取当前月份的正确方式是? A.
new Date().getMonth()
B.new Date().getMonth() + 1
✅ C.new Date().getMinutes()
(填空)将日期对象转为 yyyy-mm-dd 格式:
javascriptconst date = new Date(); const formatted = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
(纠错)找出代码错误:
javascriptlocalStorage.setItem("user", {name: "李四"}); // 错误!对象需要先用 JSON.stringify 转换
项目题
制作倒计时+存储功能 要求:
- 输入目标日期(如"2024-12-25")
- 每秒更新剩余天数/小时/分钟
- 用
localStorage
保存倒计时记录 - (拓展)添加历史记录功能
html
<!-- 示例结构 -->
<input type="datetime-local" id="targetDate">
<button id="save">保存</button>
<div id="counter">剩余:--天 --小时 --分钟</div>
<ul id="history"></ul>
<!-- dayjs 支持时间差计算 -->
<script>
function updateCounter(target) {
const now = dayjs();
const diff = target.diff(now);
if (diff <= 0) return "已到达!";
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
const mins = Math.floor((diff / (1000 * 60)) % 60);
return `${days}天 ${hours}小时 ${mins}分钟`;
}
</script>