front-standard-utils
Version:
71 lines (68 loc) • 1.91 kB
text/typescript
/**
* @description 格式化时间 + 0
* @param {number/string} number
* @returns {string|number}
*/
export const formatNumber = (number: number | string): string | number => {
const n = Number(number);
return n > 9 ? n : '0' + n;
};
/**
* @description 格式化年月日时分秒时间 2022-01-01 12:12:12
* @param {number} timestamp 时间戳
* @param {string} beforeSeparate 年月日分隔符 默认-
* @param {string} afterSeparate 时分秒分隔符 默认:
* @returns {string}
*/
export const formatDate = (
timestamp: number,
beforeSeparate: string = '-',
afterSeparate: string = ':'
): string => {
const time = new Date(timestamp);
const y = time.getFullYear();
const m = time.getMonth() + 1;
const d = time.getDate();
const h = time.getHours();
const mm = time.getMinutes();
const s = time.getSeconds();
return (
y +
beforeSeparate +
formatNumber(m) +
beforeSeparate +
formatNumber(d) +
' ' +
formatNumber(h) +
afterSeparate +
formatNumber(mm) +
afterSeparate +
formatNumber(s)
);
};
/**
* @description 格式化时间 返回 刚刚/5分钟前
* @param {number} timestamp
* @returns {string}
*/
export const getFormatTime = (timestamp: number): string => {
const time = new Date(timestamp).valueOf();
const today = new Date(
new Date(new Date().toLocaleDateString()).getTime()
).valueOf(); //获取当天0点时间戳
const now = new Date().valueOf();
let timer = (now - time) / 1000;
let tip = '';
if (timer <= 0) {
tip = '刚刚';
} else if (Math.floor(timer / 60) <= 0) {
tip = '刚刚';
} else if (timer < 3600) {
tip = Math.floor(timer / 60) + '分钟前';
} else if (timer >= 3600 && timestamp - today >= 0) {
tip = Math.floor(timer / 3600) + '小时前';
} else if (timer / 84600 <= 31) {
tip = Math.ceil(timer / 86400) + '天前';
}
return tip;
};