一般的格式化
1
2
3
4
5
//年-月-日 时:分:秒
const dateFormatter = (e)=> {
return `${e.getFullYear()}-${e.getMonth() + 1 < 10? "0" + (e.getMonth() + 1): e.getMonth() + 1
}-${e.getDate() < 10 ? "0" + e.getDate() : e.getDate()} ${e.getHours() < 10 ? "0" + e.getHours() : e.getHours()}:${e.getMinutes() < 10 ? "0" + e.getMinutes() : e.getMinutes()}`;
}
判断时间差是否在范围内
1
2
3
4
5
6
const isWithinSomeHours = (timestamp1, timestamp2, hour) => {
var millisecondsPerHour = 60 * 60 * 1000; // 一小时的毫秒数
var timeDiff = Math.abs(timestamp1 - timestamp2); // 两个时间戳的毫秒数差值
var diffHours = Math.floor(timeDiff / millisecondsPerHour); // 相差的小时数
return diffHours <= hour;
}
时间戳转时间格式(时:分)
1
2
3
4
5
6
7
8
9
10
11
12
13
const timestampToTime = (timestamp) => {
var date = new Date(timestamp * 1000);
var hours = date.getHours();
var minutes = date.getMinutes();
// 为了输出统一的格式,如:08:30
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
return hours + ":" + minutes;
}
转成指定格式 7/26 星期三 09:31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const getWeekDate = () => {
const date = new Date()
const month = date.getMonth() + 1;
const day = date.getDate();

const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
const weekday = weekdays[date.getDay()];

const hours = date.getHours();
const minutes = date.getMinutes();

const formattedDate = `${month}/${day}`;
const formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;

return `${formattedDate} ${weekday} ${formattedTime}`;
}