package com.platform.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtils { /** * 将格式为 yyyyMMddHHmmss 的字符串转换为 Date 对象 * @param dateStr 日期时间字符串,格式必须为 yyyyMMddHHmmss * @return 对应的 Date 对象 * @throws ParseException 如果字符串格式不匹配或无效 */ public static Date parseCompactDateTime(String dateStr) throws ParseException { if (dateStr == null || dateStr.length() != 14) { throw new ParseException("日期字符串格式必须为 yyyyMMddHHmmss,长度为14位", 0); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); sdf.setLenient(false); // 严格模式,不允许自动转换无效日期 return sdf.parse(dateStr); } // 可选:添加一个重载方法,允许自定义格式 public static Date parseDateTime(String dateStr, String pattern) throws ParseException { if (dateStr == null || pattern == null) { throw new ParseException("日期字符串和格式模式不能为null", 0); } SimpleDateFormat sdf = new SimpleDateFormat(pattern); sdf.setLenient(false); return sdf.parse(dateStr); } }