import http from '../../../utils/api'; const baseUrl = require('../../../utils/baseUrl'); Page({ /** * 页面的初始数据 */ data: { baseUrl: baseUrl, chatSessions: [] // 存储聊天列表数据 }, /** * 生命周期函数--监听页面加载 */ onLoad(options) { this.getsessions(); }, // 获取聊天列表 getsessions() { http.sessions({ data: {}, success: (res) => { console.log('接口返回数据:', res); if (res.code === 200 && Array.isArray(res.data)) { // 预处理数据:为每条数据添加格式化后的时间字段 const formattedSessions = res.data.map(item => { return { ...item, formattedTime: this.formatTime(item.lastMessageTime) // 新增字段,在JS里直接格式化好 }; }); this.setData({ chatSessions: formattedSessions }); } else { console.error('数据格式错误或接口异常', res); } }, fail: (err) => { console.error('请求失败', err); } }); }, // 格式化时间显示 - 兼容多种格式 formatTime(timeValue) { console.log('时间原始值:', timeValue); if (!timeValue) return ''; let date; // 判断是否是时间戳(数字或数字字符串) if (typeof timeValue === 'number' || (typeof timeValue === 'string' && /^\d+$/.test(timeValue))) { // 如果是时间戳,直接使用 date = new Date(Number(timeValue)); } // 判断是否是日期字符串 else if (typeof timeValue === 'string') { // 尝试解析字符串日期 // 将 '2026-03-06 15:50:11' 替换为 '2026/03/06 15:50:11' (兼容 iOS) const formattedStr = timeValue.replace(/-/g, '/'); date = new Date(formattedStr); } else { console.log('未知的时间格式:', timeValue); return ''; } // 检查日期是否有效 if (isNaN(date.getTime())) { console.log('无效的日期:', timeValue); return ''; } const now = new Date(); const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); const yesterday = today - 24 * 60 * 60 * 1000; const targetDate = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); if (targetDate === today) { // 今天: 显示 时:分 const hours = date.getHours().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0'); return `${hours}:${minutes}`; } else if (targetDate === yesterday) { return '昨天'; } else { // 更早: 显示 月-日 const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); return `${month}-${day}`; } }, // 跳转到聊天详情页面 goToChat(e) { console.log(e); const id = e.currentTarget.dataset.id wx.navigateTo({ url: `/pagesA/pages/expertChat/expertChat?id=${id}` }); }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh() { this.getsessions(); wx.stopPullDownRefresh(); } });