使用了useTimeAgo
和一个包含不同时间单位翻译的消息对象。给定一个日期,它将返回一个格式化的字符串表示相对于当前时间的时间差,例如"刚刚"、"2分钟前"、"10天前"等等。其中的消息对象将根据时间差的不同选择适当的单位进行翻译。最后,它使用了replaceAll
函数来移除所有双引号,这可能是为了避免出现JSON格式的字符串。
const time = new Date()
const timeFormat = (date) => {
return useTimeAgo(date, {
messages: {
justNow: "刚刚",
past: (n) => (n.match(/\d/) ? `${n}以前` : n),
future: (n) => (n.match(/\d/) ? `未来 ${n}` : n),
month: (n, past) =>
n === 1 ? (past ? "上个月" : "下个月") : `${n}个月${n > 1 ? "" : ""}`,
year: (n, past) =>
n === 1 ? (past ? "去年" : "明年") : `${n}年${n > 1 ? "" : ""}`,
day: (n, past) =>
n === 1 ? (past ? "昨天" : "明天") : `${n}天${n > 1 ? "" : ""}`,
week: (n, past) =>
n === 1 ? (past ? "上一周" : "下一周") : `${n}周${n > 1 ? "" : ""}`,
hour: (n) => `${n}小时${n > 1 ? "" : ""}`,
minute: (n) => `${n}分钟${n > 1 ? "" : ""}`,
second: (n) => `${n}秒${n > 1 ? "" : ""}`,
},
}).value.replaceAll('"', "");
};
console.log(timeFormat(time));