时间类型的相关教程参考 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date
初始化日期
有四种方式
1 2 3 4
| new Date() new Date(milliseconds) new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds)
|
上面的参数大多数都是可选的,在不指定的情况下,默认参数是0。
日期比较
直接用>、<、=进行比较
1 2 3 4 5 6 7 8 9
| var x=new Date(); x.setFullYear(2100,0,14); var today = new Date();
if (x>today){ alert("今天是2100年1月14日之前"); }else{ alert("今天是2100年1月14日之后"); }
|
日期/时间库
现在只要一百度,就是推荐 Moment.js。但是这个工具 =已经不再推荐使用了,可以参考官网 http://momentjs.cn/docs/ 的原话.好的是人家给出了一些替代工具
luxon:https://moment.github.io/luxon/#/
nodejs:https://day.nodejs.cn/
date-fns:https://date-fns.org/
js-joda:https://js-joda.github.io/js-joda/
不用库,JavaScript 一直有一个 Date 对象可以使用。
常用的时间操作
生成utc格式的时间
1 2 3 4 5 6 7
| const now = new Date(); const utcNow = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
const date = new Date('2022-01-01T00:00:00'); const utcDate = new Date(date.getTime() + date.getTimezoneOffset() * 60000);
|
生成北京时间
2023/10/9 18:14:22
1 2 3
| const now = new Date(); const beijingTime = now.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" }); console.log(beijingTime);
|
上面生成的时间中 月、日 都不是两位数
1 2 3 4
| const now = new Date(); const options = { timeZone: "Asia/Shanghai", year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }; const beijingTime = now.toLocaleString("zh-CN", options); console.log(beijingTime);
|
去掉符号
1 2 3 4
| const now = new Date(); const options = { timeZone: "Asia/Shanghai", year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }; const beijingTime = now.toLocaleString("zh-CN", options).replace(/[\/\s:]/g, ''); console.log(beijingTime);
|
生成时间字符串
生成形如 2023100909594504
1 2 3
| const now = new Date(); const beijingTime = now.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" }); const currentDateTime = beijingTime.toISOString().replace(/[-T:.Z]/g, '');
|