如何将MM/DD/YYYY格式日期转为ISO格式以查询MongoDB
问题解决思路
你的代码抛出ParseException的核心原因是解析格式与输入日期格式不匹配:输入是MM/dd/yyyy(如12/28/2022),但你用了MongoDB的ISO日期格式yyyy-MM-dd'T'HH:mm:ss.SSSXXX去解析,两者完全不兼容。
下面分两种方案解决,优先推荐Java 8+的新日期API(线程安全、无旧API的缺陷):
方案一:使用Java 8+ 推荐的java.time API(优先选择)
SimpleDateFormat是过时且线程不安全的类,推荐使用java.time包下的工具类:
import java.time.LocalDate; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; // 1. 定义输入日期的解析格式 DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); // 2. 解析输入字符串为LocalDate String fromDateStr = requestObject.get("fromDate"); String toDateStr = requestObject.get("toDate"); LocalDate fromLocalDate = LocalDate.parse(fromDateStr, inputFormatter); LocalDate toLocalDate = LocalDate.parse(toDateStr, inputFormatter); // 3. 转换为MongoDB兼容的UTC时区ISO日期格式(带时分秒和偏移量) // 起始日期取当天00:00:00,结束日期取当天23:59:59.999 ZonedDateTime fromZoned = fromLocalDate.atStartOfDay(ZoneOffset.UTC); ZonedDateTime toZoned = toLocalDate.atTime(23,59,59,999).atZone(ZoneOffset.UTC); // 格式化为目标字符串 DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; String fromIsoDate = isoFormatter.format(fromZoned); String toIsoDate = isoFormatter.format(toZoned); // 若直接用于MongoDB查询,无需转字符串,可直接传ZonedDateTime或Instant // 例如MongoDB查询条件: // collection.find(Filters.gte("dateField", fromZoned.toInstant()));
方案二:使用旧版SimpleDateFormat(仅兼容Java 8以前版本)
如果必须使用旧API,需要分两步:先解析输入格式,再格式化为目标ISO格式:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class DateConverter { public static void main(String[] args) throws ParseException { String fromDateStr = requestObject.get("fromDate"); String toDateStr = requestObject.get("toDate"); // 1. 解析输入的MM/dd/yyyy格式字符串 SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy"); inputFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // 统一时区为UTC,避免时区偏差 Date fromDate = inputFormat.parse(fromDateStr); Date toDate = inputFormat.parse(toDateStr); // 2. 格式化为MongoDB需要的ISO日期格式 SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); isoFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String fromIsoDate = isoFormat.format(fromDate); String toIsoDate = isoFormat.format(toDate); // 用于MongoDB查询 // collection.find(new BasicDBObject("dateField", new BasicDBObject("$gte", fromDate).append("$lte", toDate))); } }
关键注意事项
- 时区统一:MongoDB默认存储UTC时区的日期,转换时务必设置时区为UTC,避免本地时区导致的时间偏差。
- 查询优化:如果是用于MongoDB查询,无需将日期转为字符串,直接传递
Date(旧API)或Instant/ZonedDateTime(新API)即可,驱动会自动处理为BSON日期类型,查询效率更高。 - 输入格式校验:建议在解析前先校验输入字符串是否符合
MM/dd/yyyy格式,避免非法输入导致的异常。
内容的提问来源于stack exchange,提问作者Vinod
相关产品推荐
相关产品推荐

