fix: 统一设备时间戳避免时区偏差 (#3280)

This commit is contained in:
Tyke Chen 2026-07-13 17:36:01 +08:00
parent 03ec3bac3f
commit d9a1709f90
8 changed files with 231 additions and 36 deletions

View file

@ -304,15 +304,20 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
@Override @Override
public List<UserShowDeviceListVO> getUserDeviceList(Long userId, String agentId) { public List<UserShowDeviceListVO> getUserDeviceList(Long userId, String agentId) {
List<DeviceEntity> devices = getUserDevices(userId, agentId); List<DeviceEntity> devices = getUserDevices(userId, agentId);
return devices.stream().map(device -> { return devices.stream().map(this::toUserShowDeviceListVO).toList();
}
private UserShowDeviceListVO toUserShowDeviceListVO(DeviceEntity device) {
UserShowDeviceListVO vo = ConvertUtils.sourceToTarget(device, UserShowDeviceListVO.class); UserShowDeviceListVO vo = ConvertUtils.sourceToTarget(device, UserShowDeviceListVO.class);
vo.setDeviceType(device.getBoard()); vo.setDeviceType(device.getBoard());
// 设置UTC时间戳供前端使用时区转换 vo.setBoard(device.getBoard());
if (device.getLastConnectedAt() != null) { vo.setCreateDateTimestamp(toTimestamp(device.getCreateDate()));
vo.setLastConnectedAtTimestamp(device.getLastConnectedAt().getTime()); vo.setLastConnectedAtTimestamp(toTimestamp(device.getLastConnectedAt()));
}
return vo; return vo;
}).toList(); }
private Long toTimestamp(Date date) {
return date == null ? null : date.getTime();
} }
@Override @Override
@ -385,17 +390,11 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
.like(StringUtils.isNotBlank(dto.getKeywords()), "alias", dto.getKeywords())); .like(StringUtils.isNotBlank(dto.getKeywords()), "alias", dto.getKeywords()));
// 循环处理page获取回来的数据,返回需要的字段 // 循环处理page获取回来的数据,返回需要的字段
List<UserShowDeviceListVO> list = page.getRecords().stream().map(device -> { List<UserShowDeviceListVO> list = page.getRecords().stream().map(device -> {
UserShowDeviceListVO vo = ConvertUtils.sourceToTarget(device, UserShowDeviceListVO.class); UserShowDeviceListVO vo = toUserShowDeviceListVO(device);
// 把最后修改的时间,改为简短描述的时间 // 把最后修改的时间,改为简短描述的时间
vo.setRecentChatTime(DateUtils.getShortTime(device.getUpdateDate())); vo.setRecentChatTime(DateUtils.getShortTime(device.getUpdateDate()));
sysUserUtilService.assignUsername(device.getUserId(), sysUserUtilService.assignUsername(device.getUserId(),
vo::setBindUserName); vo::setBindUserName);
vo.setDeviceType(device.getBoard());
vo.setBoard(device.getBoard());
// 设置UTC时间戳供前端使用时区转换
if (device.getLastConnectedAt() != null) {
vo.setLastConnectedAtTimestamp(device.getLastConnectedAt().getTime());
}
return vo; return vo;
}).toList(); }).toList();
// 计算页数 // 计算页数

View file

@ -38,10 +38,13 @@ public class UserShowDeviceListVO {
@Schema(description = "最近对话时间") @Schema(description = "最近对话时间")
private String recentChatTime; private String recentChatTime;
@Schema(description = "最后连接时间(UTC毫秒)") @Schema(description = "最后连接时间戳(毫秒)", type = "string", example = "1783689702000")
private Long lastConnectedAtTimestamp; private Long lastConnectedAtTimestamp;
@Schema(description = "绑定时间") @Schema(description = "绑定时间戳(毫秒)", type = "string", example = "1783689702000")
private Long createDateTimestamp;
@Schema(description = "绑定时间(兼容字段,请使用 createDateTimestamp)", deprecated = true)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "UTC") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "UTC")
private Date createDate; private Date createDate;

View file

@ -0,0 +1,87 @@
package xiaozhi.modules.device.service.impl;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.vo.UserShowDeviceListVO;
import xiaozhi.modules.security.config.WebMvcConfig;
@DisplayName("设备时间序列化回归测试")
class DeviceTimeSerializationTest {
@ParameterizedTest(name = "浏览器时区 {0}")
@ValueSource(strings = { "Asia/Shanghai", "America/Sao_Paulo" })
@DisplayName("#3280 绑定时间和最后连接时间在任意浏览器时区都表示同一时刻")
void serializedDeviceTimesDescribeTheSameInstantAcrossBrowserTimeZones(String browserTimeZone) {
Instant connectedAt = Instant.parse("2026-07-10T13:21:42Z");
DeviceEntity entity = new DeviceEntity();
entity.setCreateDate(Date.from(connectedAt));
entity.setLastConnectedAt(Date.from(connectedAt));
DeviceServiceImpl deviceService = serviceReturning(entity);
UserShowDeviceListVO device = deviceService.getUserDeviceList(1L, "agent-id").getFirst();
ObjectMapper objectMapper = new WebMvcConfig().jackson2HttpMessageConverter().getObjectMapper();
JsonNode payload = objectMapper.valueToTree(device);
Instant createDate = Instant.ofEpochMilli(
Long.parseLong(payload.path("createDateTimestamp").asText()));
Instant lastConnectedAt = Instant.ofEpochMilli(
Long.parseLong(payload.path("lastConnectedAtTimestamp").asText()));
ZoneId browserZone = ZoneId.of(browserTimeZone);
assertAll(
() -> assertTrue(payload.path("createDateTimestamp").isTextual(),
"Long 时间戳必须遵循现有 JSON 契约序列化为字符串"),
() -> assertTrue(payload.path("lastConnectedAtTimestamp").isTextual(),
"Long 时间戳必须遵循现有 JSON 契约序列化为字符串"),
() -> assertEquals(connectedAt, createDate,
"createDateTimestamp 必须保留源时间点"),
() -> assertEquals(connectedAt, lastConnectedAt,
"lastConnectedAtTimestamp 必须保留源时间点"),
() -> assertEquals(lastConnectedAt.atZone(browserZone).toLocalDateTime(),
createDate.atZone(browserZone).toLocalDateTime(),
"绑定时间和最后连接时间在同一浏览器中必须显示为相同的本地时间"),
() -> assertTrue(payload.path("createDate").isTextual(),
"兼容字段 createDate 必须继续保留"));
}
@Test
@DisplayName("时间为空时新旧字段均保持 null")
void nullDeviceTimesRemainNull() {
DeviceEntity entity = new DeviceEntity();
DeviceServiceImpl deviceService = serviceReturning(entity);
UserShowDeviceListVO device = deviceService.getUserDeviceList(1L, "agent-id").getFirst();
ObjectMapper objectMapper = new WebMvcConfig().jackson2HttpMessageConverter().getObjectMapper();
JsonNode payload = objectMapper.valueToTree(device);
assertAll(
() -> assertTrue(payload.path("createDateTimestamp").isNull()),
() -> assertTrue(payload.path("lastConnectedAtTimestamp").isNull()),
() -> assertTrue(payload.path("createDate").isNull()));
}
private DeviceServiceImpl serviceReturning(DeviceEntity entity) {
return new DeviceServiceImpl(null, null, null, null, null, null) {
@Override
public List<DeviceEntity> getUserDevices(Long userId, String agentId) {
return List.of(entity);
}
};
}
}

View file

@ -5,6 +5,7 @@
"scripts": { "scripts": {
"serve": "vue-cli-service serve", "serve": "vue-cli-service serve",
"build": "vue-cli-service build", "build": "vue-cli-service build",
"test:unit": "node --test tests/*.test.mjs",
"analyze": "cross-env ANALYZE=true vue-cli-service build" "analyze": "cross-env ANALYZE=true vue-cli-service build"
}, },
"dependencies": { "dependencies": {

View file

@ -0,0 +1,41 @@
export function hasTimestampValue(timestamp) {
if (timestamp === null || timestamp === undefined) return false;
return typeof timestamp !== 'string' || timestamp.trim() !== '';
}
export function parseTimestamp(timestamp) {
if (!hasTimestampValue(timestamp)) return null;
if (typeof timestamp !== 'number' && typeof timestamp !== 'string') return null;
const normalizedTimestamp = typeof timestamp === 'string' ? timestamp.trim() : timestamp;
const parsedTimestamp = Number(normalizedTimestamp);
if (!Number.isFinite(parsedTimestamp)) return null;
return Number.isNaN(new Date(parsedTimestamp).getTime()) ? null : parsedTimestamp;
}
export function parseLegacyDate(dateValue) {
if (!dateValue) return null;
const timestamp = new Date(dateValue).getTime();
return Number.isNaN(timestamp) ? null : timestamp;
}
export function formatTimestamp(timestamp, formatter = value => new Date(value).toLocaleString()) {
const parsedTimestamp = parseTimestamp(timestamp);
return parsedTimestamp === null ? '-' : formatter(parsedTimestamp);
}
export function formatCreateDate(timestamp, legacyDate, formatter) {
if (!hasTimestampValue(timestamp)) return legacyDate || '-';
return formatTimestamp(timestamp, formatter);
}
export function compareTimestamps(firstTimestamp, secondTimestamp) {
const firstIsValid = Number.isFinite(firstTimestamp);
const secondIsValid = Number.isFinite(secondTimestamp);
if (firstIsValid && secondIsValid) return firstTimestamp - secondTimestamp;
if (firstIsValid) return -1;
if (secondIsValid) return 1;
return 0;
}

View file

@ -120,7 +120,7 @@
<i class="el-icon-time"></i> <i class="el-icon-time"></i>
<div class="stat-content"> <div class="stat-content">
<div class="stat-label">{{ $t('addressBookManagement.addTime') }}</div> <div class="stat-label">{{ $t('addressBookManagement.addTime') }}</div>
<div class="stat-value">{{ selectedDevice.createDate || '-' }}</div> <div class="stat-value">{{ formatDeviceCreateDate(selectedDevice) }}</div>
</div> </div>
</div> </div>
<div class="stat-item"> <div class="stat-item">
@ -207,6 +207,7 @@ import Api from "@/apis/api.js";
import AddressBookApi from "@/apis/module/addressBook.js"; import AddressBookApi from "@/apis/module/addressBook.js";
import MacAddressMask from "@/components/MacAddressMask.vue"; import MacAddressMask from "@/components/MacAddressMask.vue";
import CustomButton from "@/components/CustomButton.vue"; import CustomButton from "@/components/CustomButton.vue";
import { formatCreateDate, parseTimestamp } from '@/utils/deviceTime.mjs';
export default { export default {
name: "AddressBookManagement", name: "AddressBookManagement",
@ -281,6 +282,7 @@ export default {
remarks: device.alias || '', remarks: device.alias || '',
online: false, online: false,
createDate: device.createDate, createDate: device.createDate,
createDateTimestamp: device.createDateTimestamp,
lastConnectedAt: device.lastConnectedAtTimestamp, lastConnectedAt: device.lastConnectedAtTimestamp,
deviceStatus: 'offline' deviceStatus: 'offline'
})); }));
@ -526,9 +528,10 @@ export default {
this.isEditingAgentName = false; this.isEditingAgentName = false;
}, },
getTimeAgo(timestamp) { getTimeAgo(timestamp) {
if (!timestamp) return '-'; const ts = parseTimestamp(timestamp);
if (ts === null) return '-';
const now = new Date(); const now = new Date();
const date = new Date(Number(timestamp)); const date = new Date(ts);
const diff = now - date; const diff = now - date;
const seconds = Math.floor(diff / 1000); const seconds = Math.floor(diff / 1000);
@ -545,6 +548,10 @@ export default {
if (months < 12) return this.$t('addressBookManagement.monthsAgo', { months }); if (months < 12) return this.$t('addressBookManagement.monthsAgo', { months });
return this.$t('addressBookManagement.yearsAgo', { years }); return this.$t('addressBookManagement.yearsAgo', { years });
}, },
formatDeviceCreateDate(device) {
if (!device) return '-';
return formatCreateDate(device.createDateTimestamp, device.createDate);
},
getDeviceAvatar(deviceId) { getDeviceAvatar(deviceId) {
// 根据 deviceId 计算 MD5,选择对应的头像 // 根据 deviceId 计算 MD5,选择对应的头像
const avatars = [ const avatars = [

View file

@ -103,6 +103,14 @@ import VersionFooter from "@/components/VersionFooter.vue";
import MacAddressMask from "@/components/MacAddressMask.vue"; import MacAddressMask from "@/components/MacAddressMask.vue";
import CustomButton from "@/components/CustomButton.vue"; import CustomButton from "@/components/CustomButton.vue";
import CustomTable from "@/components/CustomTable.vue"; import CustomTable from "@/components/CustomTable.vue";
import {
compareTimestamps,
formatCreateDate,
formatTimestamp,
hasTimestampValue,
parseLegacyDate,
parseTimestamp,
} from '@/utils/deviceTime.mjs';
export default { export default {
components: { components: {
@ -327,26 +335,31 @@ export default {
this.loading = false; this.loading = false;
if (data.code === 0) { if (data.code === 0) {
this.deviceList = data.data.map(device => { this.deviceList = data.data.map(device => {
const hasCreateDateTimestamp = hasTimestampValue(device.createDateTimestamp);
const rawBindTime = hasCreateDateTimestamp
? parseTimestamp(device.createDateTimestamp)
: parseLegacyDate(device.createDate);
return { return {
device_id: device.id, device_id: device.id,
model: device.board, model: device.board,
firmwareVersion: device.appVersion, firmwareVersion: device.appVersion,
macAddress: device.macAddress, macAddress: device.macAddress,
bindTime: device.createDate, bindTime: formatCreateDate(device.createDateTimestamp, device.createDate),
lastConversation: device.lastConnectedAtTimestamp lastConversation: formatTimestamp(device.lastConnectedAtTimestamp),
? this.formatRelativeTime(device.lastConnectedAtTimestamp)
: '-',
remark: device.alias, remark: device.alias,
_originalRemark: device.alias, _originalRemark: device.alias,
isEdit: false, isEdit: false,
_submitting: false, _submitting: false,
otaSwitch: device.autoUpdate === 1, otaSwitch: device.autoUpdate === 1,
rawBindTime: new Date(device.createDate).getTime(), rawBindTime,
selected: false, selected: false,
deviceStatus: 'offline' deviceStatus: 'offline'
}; };
}) })
.sort((a, b) => a.rawBindTime - b.rawBindTime); .sort((firstDevice, secondDevice) => compareTimestamps(
firstDevice.rawBindTime,
secondDevice.rawBindTime,
));
this.activeSearchKeyword = ""; this.activeSearchKeyword = "";
this.searchKeyword = ""; this.searchKeyword = "";
@ -429,14 +442,6 @@ export default {
const version = row.firmwareVersion.replace(/\./g, ''); const version = row.firmwareVersion.replace(/\./g, '');
return Number(version) >= 200; return Number(version) >= 200;
}, },
formatRelativeTime(timestamp) {
if (!timestamp) return '-';
const ts = Number(timestamp);
if (isNaN(ts)) return '-';
const date = new Date(ts);
if (isNaN(date.getTime())) return '-';
return date.toLocaleString();
},
} }
}; };
</script> </script>

View file

@ -0,0 +1,52 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
compareTimestamps,
formatCreateDate,
formatTimestamp,
parseTimestamp,
} from '../src/utils/deviceTime.mjs';
const TIMESTAMP = 1783689702000;
test('accepts epoch milliseconds as a number or numeric string', () => {
assert.equal(parseTimestamp(TIMESTAMP), TIMESTAMP);
assert.equal(parseTimestamp(String(TIMESTAMP)), TIMESTAMP);
assert.equal(parseTimestamp(` ${TIMESTAMP} `), TIMESTAMP);
});
test('rejects missing, invalid and non-scalar timestamp values', () => {
const invalidValues = [null, undefined, '', ' ', 'invalid', true, {}, [], Infinity, Number.MAX_VALUE];
invalidValues.forEach(value => assert.equal(parseTimestamp(value), null));
assert.equal(formatTimestamp('invalid'), '-');
});
test('falls back to the legacy createDate only when the timestamp is missing', () => {
const legacyDate = '2026-07-10 21:21:42';
const formatter = timestamp => `local:${timestamp}`;
assert.equal(formatCreateDate(undefined, legacyDate, formatter), legacyDate);
assert.equal(formatCreateDate('', legacyDate, formatter), legacyDate);
assert.equal(formatCreateDate('invalid', legacyDate, formatter), '-');
assert.equal(formatCreateDate(String(TIMESTAMP), legacyDate, formatter), `local:${TIMESTAMP}`);
});
test('formats the same instant consistently in each browser time zone', () => {
const formatter = timeZone => timestamp => new Date(timestamp).toLocaleString('en-US', { timeZone });
for (const timeZone of ['Asia/Shanghai', 'America/Sao_Paulo']) {
assert.equal(
formatTimestamp(TIMESTAMP, formatter(timeZone)),
formatTimestamp(String(TIMESTAMP), formatter(timeZone)),
);
}
});
test('sorts valid epoch values first and leaves invalid values at the end', () => {
const timestamps = [null, TIMESTAMP + 1, undefined, TIMESTAMP];
assert.deepEqual(timestamps.sort(compareTimestamps), [TIMESTAMP, TIMESTAMP + 1, null, undefined]);
assert.equal(compareTimestamps(null, undefined), 0);
});