tiefen_space_h5/utils/tools.js

95 lines
2.4 KiB
JavaScript
Raw Normal View History

2024-07-02 23:08:38 +08:00
//格式化时间戳
export function formatDeadline(timestamp) {
2024-07-06 11:05:19 +08:00
const date = new Date(timestamp * 1000); // 时间戳以秒为单位需要乘以1000转换成毫秒
const year = date.getFullYear();
const month = ("0" + (date.getMonth() + 1)).slice(-2);
const day = ("0" + date.getDate()).slice(-2);
const hours = ("0" + date.getHours()).slice(-2);
const minutes = ("0" + date.getMinutes()).slice(-2);
const seconds = ("0" + date.getSeconds()).slice(-2);
2024-07-02 23:08:38 +08:00
2024-07-06 11:05:19 +08:00
return `${year}${month}${day}${hours}:${minutes}:${seconds}`;
}
2024-10-22 17:24:02 +08:00
export function formatTimestamp(timestamp) {
const now = new Date();
const date = new Date(timestamp * 1000);
// 检查是否是今天
if (now.toDateString() === date.toDateString()) {
return date.toLocaleTimeString(undefined, {
hour: "numeric",
minute: "numeric",
});
}
// 获取昨天的日期
const yesterday = new Date(now);
yesterday.setDate(now.getDate() - 1);
// 检查是否是昨天
if (yesterday.toDateString() === date.toDateString()) {
return `昨天 ${date.getHours()}:${String(date.getMinutes()).padStart(
2,
"0"
)}`;
}
// 检查是否是今年
if (now.getFullYear() === date.getFullYear()) {
return `${
date.getMonth() + 1
}-${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(
2,
"0"
)}`;
}
// 不是今年,返回完整日期和时间
return `${date.getFullYear()}-${
date.getMonth() + 1
}-${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(
2,
"0"
)}`;
}
2024-07-06 11:05:19 +08:00
// 防抖函数
export function debounce(fn, delay) {
let timer = null;
return (fnn) => {
//清除上一次的延时器
if (timer) {
clearTimeout(timer);
// return;
2024-08-05 18:59:30 +08:00
// console.log(timer);
2024-07-06 11:05:19 +08:00
}
//重新设置新的延时器
timer = setTimeout(() => {
//修改this指向问题
// fn.apply(this,value)
fn(fnn);
}, delay);
};
}
2024-07-06 16:03:15 +08:00
export function utf8Length(str) {
let length = 0;
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (code < 0x80) {
// 0xxxxxxx
length += 0.5;
} else if (code < 0x800) {
// 110xxxxx 10xxxxxx
length += 2;
} else if (code < 0x10000) {
// 1110xxxx 10xxxxxx 10xxxxxx
length += 1;
} else if (code <= 0x10ffff) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
length += 4;
}
}
return length;
}