Angular 2:12小时制时间排序及24转12小时制显示问题
解决12小时制时间排序与展示问题
我来帮你搞定这个时间排序和格式展示的问题,分两种场景给你清晰的解决方案:
一、把已排序的24小时制时间转为12小时制展示
你现在已经通过24小时制字符串完成了正确排序,问题出在展示时无法用datepipe转成AM/PM格式——核心原因是你存的open_time_time是HH:mm格式的纯字符串,datepipe需要可解析的完整时间(带日期或时间戳)才能正确转换。这里有两种简单的解决思路:
思路1:在数据处理时直接生成12小时制展示字段
修改你现有的map函数,同时生成24小时制(用于排序)和12小时制(用于展示)的字段,用moment直接格式化:
this.timings.Mon = res.timings.filter(x => x.open_time && x.close_time && x.day === 'Mon').map(function (x) { // 先把UTC时间转成moment对象(local()可根据需求调整时区) const openMoment = moment.utc(x.open_time).local(); const closeMoment = moment.utc(x.close_time).local(); return { id: x.id, // 24小时制字符串,用于排序 open_time_time: openMoment.format('HH:mm'), // 12小时制字符串,直接用于展示 open_time_12h: openMoment.format('hh:mm A'), open_time: x.open_time, close_time_time: closeMoment.format('HH:mm'), close_time_12h: closeMoment.format('hh:mm A'), close_time: x.close_time, working: x.working }; });
之后排序逻辑保持不变,展示时直接用open_time_12h字段即可,不用再依赖datepipe。
思路2:给datepipe提供可解析的时间格式
如果你坚持要用datepipe,需要给它传递完整的时间格式(比如拼接一个固定日期):
<!-- Angular模板示例 --> {{ '2000-01-01 ' + item.open_time_time | date:'hh:mm a' }}
这样datepipe能识别完整的时间字符串,正确输出AM/PM格式。
二、直接排序12小时制时间
如果你的数据源本身是12小时制的(比如"04:45 AM"这种格式),不能直接用字符串排序(比如"10:00 AM"字符串会比"09:00 PM"大,但实际时间更早),必须先转成时间对象再比较:
// 假设你的时间数组是12小时制字符串 const timeList12h = ["09:00 PM", "04:45 AM", "03:00 PM", "09:00 AM", "09:30 PM"]; timeList12h.sort((timeA, timeB) => { // 用moment把12小时制字符串转成时间戳 const timestampA = moment(timeA, 'hh:mm A').valueOf(); const timestampB = moment(timeB, 'hh:mm A').valueOf(); // 比较时间戳大小实现排序 return timestampA - timestampB; }); // 排序后结果:["04:45 AM", "09:00 AM", "03:00 PM", "09:00 PM", "09:30 PM"]
小建议
其实最灵活的方式是保留原始的moment/Date对象用于排序,展示时再按需格式化。这样既保证排序的准确性(避免字符串排序的潜在问题),又能轻松切换24/12小时制展示:
// map时保留moment对象 this.timings.Mon = res.timings.filter(x => x.open_time && x.close_time && x.day === 'Mon').map(x => ({ id: x.id, openMoment: moment.utc(x.open_time).local(), closeMoment: moment.utc(x.close_time).local(), working: x.working })); // 直接用moment对象排序 this.timings.Mon.sort((a, b) => a.openMoment.isBefore(b.openMoment) ? -1 : 1); // 展示时格式化: // 24小时制:item.openMoment.format('HH:mm') // 12小时制:item.openMoment.format('hh:mm A')
内容的提问来源于stack exchange,提问作者Aashiq Rathnadas
相关产品推荐
相关产品推荐

