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

Java 11中Mock指定格式日期及Firestore日期解析验证求助

Java 11中Mock指定时间点的Date对象及Firestore日期解析验证

核心澄清

Date对象本身没有格式,它只是一个记录UTC毫秒数的时间戳。你看到的不同格式字符串,只是对这个时间戳的不同格式化输出,而非Date对象的固有属性。你的代码生成的Date格式不符合预期,本质是时间点不对,或后续格式化逻辑有误。

一、Mock目标时间点的Date对象

如果你需要的是对应Jun 1, 2024, 8:07:29.920 PM这个时间点的Date对象(假设时区为America/New_York),直接构造该时间点再转成Date即可:

// 定义目标时间字符串和匹配的格式器
String targetDateStr = "Jun 1, 2024, 8:07:29.920 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d, yyyy, h:mm:ss.SSS a")
        .withLocale(Locale.US)
        .withZone(ZoneId.of("America/New_York"));

// 解析为ZonedDateTime后转成Date
ZonedDateTime targetZdt = ZonedDateTime.parse(targetDateStr, formatter);
Date targetDate = Date.from(targetZdt.toInstant());

// Mock返回该Date对象
Mockito.when(mockPriceMap.get("startDate")).thenReturn(targetDate);

此时生成的Date对象,用上述格式器格式化就能得到你需要的字符串;直接打印Date会显示默认格式,但底层时间点是正确的。

二、解析Firestore日期并验证

如果Firestore存储的是该格式的字符串,用同样的格式器解析后即可与当前日期对比:

// 从Firestore取出的日期字符串
String firestoreDateStr = "Jun 1, 2024, 8:07:29.920 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d, yyyy, h:mm:ss.SSS a")
        .withLocale(Locale.US)
        .withZone(ZoneId.of("America/New_York"));

// 解析为ZonedDateTime
ZonedDateTime firestoreZdt = ZonedDateTime.parse(firestoreDateStr, formatter);

// 获取当前时间(指定相同时区避免偏差)
ZonedDateTime currentZdt = ZonedDateTime.now(ZoneId.of("America/New_York"));

// 示例验证逻辑:判断Firestore日期是否早于当前时间
boolean isBeforeCurrent = firestoreZdt.isBefore(currentZdt);

// 或通过时间戳对比(转为Date后)
Date firestoreDate = Date.from(firestoreZdt.toInstant());
Date currentDate = Date.from(currentZdt.toInstant());
boolean isTimestampMatch = firestoreDate.getTime() == currentDate.getTime();

关键注意事项

  • 必须指定明确的时区,避免因默认时区差异导致时间偏差。
  • 格式化/解析统一使用DateTimeFormatter(Java 8+官方推荐),不要依赖Date.toString()的默认输出。
  • 如果Firestore存储的是Timestamp类型而非字符串,直接调用Timestamp.toDate()转成Date即可,无需字符串解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:26:10