前端常用时间操作汇总
(1)获取中国标准时间:
let now = new Date();
// Thu Nov 14 2024 17:13:49 GMT+0800 (中国标准时间)
(2)获取年份:
let year = now.getFullYear();
// 2024
(3)获取月份:
let month = now.getMonth() + 1; // 加1因为月份是从0开始的
// 11
(4)获取日期
let day = now.getDate();
// 11
(5)获取时:
let hour = now.getHours();
// 17
(6)获取分:
let minute = now.getMinutes();
// 19
(7)获取秒:
let second = now.getSeconds();
// 56
(8)获取时间戳:
let timestamp = now.getTime();
// 1731576050974
(9)根据时间戳转为中国标准时间:
let date = new Date(1731576050974);
// Thu Nov 14 2024 17:20:50 GMT+0800 (中国标准时间)
(10)比较时间大小:
let a = '2024-10-12 12:14:56';
let now = new Date();
let result = a > b;
// false
(11)当前时间加三天:
const threeDay = now.setDate(now.getDate() + 3); // 3天后到期
// 1731576503162
(12)el-date-picker组件限制可选范围:
1、限制只能选当前及之后的时间
:picker-options=" {disabledDate: (time) => {return time.getTime() < Date.now() - 1 * 24 * 60 * 60 * 1000;}
}"
2、限制规定时间之前都不能选
:picker-options=" {disabledDate: (time) => {return time.getTime() < new Date('1999-12-31').getTime();}
}"