Flutter中如何将创建时间转换为「X小时前」类相对时间显示?
如何将绝对时间转换为相对时间
核心逻辑是计算目标时间与当前时间的时间差,再根据差值范围映射到对应的相对时间描述。以下是几种主流编程语言的实现方案:
Python 实现
from datetime import datetime def get_relative_time(create_time_str): # 解析输入的时间字符串(格式:YYYY-MM-DD HH:MM:SS) create_time = datetime.strptime(create_time_str, "%Y-%m-%d %H:%M:%S") now = datetime.now() time_diff = now - create_time # 计算各单位差值 seconds = time_diff.total_seconds() minutes = seconds // 60 hours = minutes // 60 days = hours // 24 if seconds < 60: return "刚刚" elif minutes < 60: return f"{int(minutes)}分钟前" elif hours < 24: return f"{int(hours)}小时前" elif days < 30: return f"{int(days)}天前" else: # 超过30天返回原时间格式 return create_time_str # 测试示例 print(get_relative_time("2023-01-13 10:35:52"))
JavaScript 实现
function getRelativeTime(createTimeStr) { // 解析时间字符串为Date对象 const createTime = new Date(createTimeStr); const now = new Date(); const timeDiff = now.getTime() - createTime.getTime(); // 转换为各单位差值 const seconds = Math.floor(timeDiff / 1000); const minutes = Math.floor(seconds / 60); const hours = Math.floor(minutes / 60); const days = Math.floor(hours / 24); if (seconds < 60) { return "刚刚"; } else if (minutes < 60) { return `${minutes}分钟前`; } else if (hours < 24) { return `${hours}小时前`; } else if (days < 30) { return `${days}天前`; } else { // 超过30天返回原时间 return createTimeStr; } } // 测试示例 console.log(getRelativeTime("2023-01-13 10:35:52"));
关键注意事项
- 时间解析时要确保格式严格匹配输入字符串,若时间带时区信息,需在解析阶段额外处理时区偏移。
- 可根据需求扩展逻辑,比如增加“周”“月”的判断,或调整时间边界(如超过30天返回“X个月前”)。
- 部分语言有现成工具库可简化操作(如Python的
arrow、JavaScript的dayjs),但新手先手动实现更有助于理解底层逻辑。
内容的提问来源于stack exchange,提问作者Diljith
相关产品推荐
相关产品推荐

