React Native中使用Moment.js计算预约结束剩余时长的实现方案
基于Moment.js的预约剩余时长计算方案
核心实现思路
- 用Moment的
diff()方法计算结束时间与当前时间的差值 - 将总分钟差值拆分为小时和剩余分钟两部分,按实际场景格式化展示
- 处理边界情况:预约已结束时展示兜底文案
代码实现
第一步:封装剩余时长计算工具函数
// 入参为预约的end_date字段,返回格式化后的剩余时长字符串 const getRemainingTime = (endDateStr) => { const endTime = moment(endDateStr); const now = moment(); // 结束时间早于当前时间,说明预约已结束 if (endTime.isBefore(now)) { return '已结束'; } // 计算两个时间的总分钟差值 const diffMinutes = endTime.diff(now, 'minutes'); // 拆分小时和剩余分钟 const hours = Math.floor(diffMinutes / 60); const minutes = diffMinutes % 60; // 按时长区间格式化 if (hours === 0) { return `${minutes}分钟`; } return `${hours}小时${minutes}分钟`; }
第二步:修改业务组件代码
const ActiveSession = ({navigation}) => { const {bookings} = React.useContext(StateContext); // 若需要实时更新剩余时长,可添加以下定时器逻辑,不需要可以删除 const [, setUpdateFlag] = React.useState(0); React.useEffect(() => { // 每分钟刷新一次时长计算 const timer = setInterval(() => { setUpdateFlag(prev => prev + 1); }, 60 * 1000); return () => clearInterval(timer); }, []); return ( <> {bookings.map((booking, index) => ( // 把key从index改成booking.id,符合React列表渲染最佳实践,避免渲染异常 <View style={styles.subContainer} key={booking.id}> <View style={styles.topbar}> <Image style={styles.tinyLogo} source={{uri: booking.pod.location.image}} /> <View> <Text> <Text style={{fontWeight: 'bold'}}>{booking.pod.name}</Text> </Text> <Text>{`Time left - ${getRemainingTime(booking.end_date)}`}</Text> </View> </View> </View> ))} </> ) }
注意事项
- 如果你的
end_date字段是UTC时间,需要将const endTime = moment(endDateStr)修改为const endTime = moment.utc(endDateStr).local(),先转成用户本地时区再计算,避免时差错误 - 如果不需要实时更新剩余时长,直接删除定时器相关逻辑即可,不影响基础功能使用
内容的提问来源于stack exchange,提问作者Asher
相关产品推荐
相关产品推荐

