You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java替换JSON时间字段并校验其与当前时间的误差范围

解决方案

原有代码问题

  • 直接使用assertEquals对比时间字符串,要求两个时间完全一致才能通过,不符合近似匹配需求
  • 代码中存在无效逻辑foundObj.put(new_time, foundObj).getString("insert_time");,该操作既无用还可能引发JSON结构异常,需要删除
  • 时间格式化未匹配时区,返回的insert_time是UTC时区(后缀带Z),如果本地时区和UTC不一致会导致时间计算偏差

修改后代码

@Test
public void testExampleMessageToJson() throws Throwable {
    log.info("\n\nTesting persist service [message to json]?\n");

    //Setup
    String rawJson = TestUtils.getResourceMessage("examples/life.json");
    String tip_identifier_uuid = "12345678-1234-1234-1234-123456789112";
    // 匹配返回的UTC时间格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    log.info("Raw Json:\n():", rawJson); 
    assertTrue(StringUtils.isNotBlank(rawJson));

    //Test
    JSONObject foundObj = persistService.messageToJson(rawJson); 
    assertNotNull(foundObj);

    //Verify
    // 校验uuid
    String new_uuid = foundObj.getJSONObject("user_interface_fields").getJSONObject("tip_identifier").getString("uuid");
    assertEquals(tip_identifier_uuid , new_uuid); 

    // 校验时间差在1秒内
    String insertTimeStr = foundObj.getString("insert_time");
    Date insertTime = sdf.parse(insertTimeStr);
    long diffMs = Math.abs(System.currentTimeMillis() - insertTime.getTime());
    assertTrue("时间差超过1秒,实际差为" + diffMs + "毫秒", diffMs < 1000);

    log.info("\n\nTesting persist service [message to json] COMPLETE!\n");
}

核心修改逻辑

  • 新增匹配UTC时区的时间格式化工具,将返回的insert_time字符串解析为时间戳
  • 计算返回时间和当前系统时间的差值绝对值,判断是否小于1000毫秒
  • 保留原有uuid校验逻辑,删除无效代码
  • 校验逻辑增加自定义错误提示,测试失败时可以直接看到实际时间差值方便排查

内容的提问来源于stack exchange,提问作者Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:15:03