Files
knowai/utils/date.ts
tobegold574 6a81b7bb13
Some checks reported errors
continuous-integration/drone/push Build was killed
feat(image): 新建 knowai-core:1.0.0 镜像并完成推送
- 搭建 api、auth、utils 等逻辑模块
- 通过 tsc、eslint、vitest 测试验证

BREAKING CHANGE: 新镜像分支
2025-11-10 20:20:25 +08:00

84 lines
2.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 日期格式化工具
export const dateUtils = {
// 格式化日期
formatDate: (date: Date | string, format = 'YYYY-MM-DD'): string => {
const d = new Date(date);
if (isNaN(d.getTime())) {
return '';
}
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
const hours = String(d.getHours()).padStart(2, '0');
const minutes = String(d.getMinutes()).padStart(2, '0');
const seconds = String(d.getSeconds()).padStart(2, '0');
return format
.replace('YYYY', String(year))
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
},
// 获取相对时间2小时前
getRelativeTime: (date: Date | string): string => {
const now = new Date();
const target = new Date(date);
const diffMs = now.getTime() - target.getTime();
// 如果目标时间在未来,返回绝对时间
if (diffMs < 0) {
return dateUtils.formatDate(target, 'YYYY-MM-DD HH:mm');
}
const diffSeconds = Math.floor(diffMs / 1000);
const diffMinutes = Math.floor(diffSeconds / 60);
const diffHours = Math.floor(diffMinutes / 60);
const diffDays = Math.floor(diffHours / 24);
const diffWeeks = Math.floor(diffDays / 7);
const diffMonths = Math.floor(diffDays / 30);
const diffYears = Math.floor(diffDays / 365);
if (diffSeconds < 60) {
return '刚刚';
} else if (diffMinutes < 60) {
return `${diffMinutes}分钟前`;
} else if (diffHours < 24) {
return `${diffHours}小时前`;
} else if (diffDays < 7) {
return `${diffDays}天前`;
} else if (diffWeeks < 4) {
return `${diffWeeks}周前`;
} else if (diffMonths < 12) {
return `${diffMonths}个月前`;
} else {
return `${diffYears}年前`;
}
},
// 检查是否是今天
isToday: (date: Date | string): boolean => {
const today = new Date();
const target = new Date(date);
return today.getFullYear() === target.getFullYear() &&
today.getMonth() === target.getMonth() &&
today.getDate() === target.getDate();
},
// 检查是否是昨天
isYesterday: (date: Date | string): boolean => {
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const target = new Date(date);
return yesterday.getFullYear() === target.getFullYear() &&
yesterday.getMonth() === target.getMonth() &&
yesterday.getDate() === target.getDate();
}
};