Java中String转Date异常:中午12:00-12:59被转为午夜时段
解决String转Date时中午12点被解析为午夜的问题
这个坑我之前踩过!核心问题出在你用的时间格式符上:
hh代表的是12小时制的小时(取值范围是1-12),当输入的时间是中午12:00-12:59时,12小时制的12会被SimpleDateFormat识别为午夜的0点,这就导致了时间转换错误。- 而
HH才是24小时制的小时(取值范围是0-23),这才是符合你需求的格式符。
修正后的SimpleDateFormat版本
首先直接修改格式串,同时别忘了处理parse方法抛出的ParseException:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public static Date dateConv1(String s) throws ParseException { // 把hh替换为HH,切换到24小时制解析 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss"); return formatter.parse(s); }
更推荐的Java 8+新日期API方案
另外要提醒你:SimpleDateFormat是线程不安全的,在多线程场景下很容易出问题。如果你的项目是Java 8及以上版本,强烈推荐使用java.time包下的日期时间类,它们不仅线程安全,设计也更合理:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.ZoneId; import java.util.Date; public static Date dateConv1(String s) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss"); // 先解析为LocalDateTime(Java 8+的日期时间类) LocalDateTime localDateTime = LocalDateTime.parse(s, formatter); // 如果需要转换成旧的java.util.Date return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); }
这样修改后,中午12点的时间就能被正确解析啦!
内容的提问来源于stack exchange,提问作者Beata
相关产品推荐
相关产品推荐

