首页 > 解决方案 > 如何在 Java 中将字符串 AM/PM 日期转换为时间戳?

问题描述

我想解析一个包含从字符串到时间戳的 AM/PM 格式的日期。

虽然当我尝试解析这个日期时:Dec 31 2017 12:00AM

我得到一个

Exception in thread "main" java.text.ParseException: Unparseable date: "Dec 31 2017 12:00AM"
    at java.text.DateFormat.parse(Unknown Source)
    at test.DatteTest.main(DatteTest.java:16)

我的代码:

String endDate = "Dec 31 2017 12:00AM";         
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy hh:mmaa");
Date parsedDate = dateFormat.parse(endDate);
Timestamp timestamp = new Timestamp(parsedDate.getTime());
System.out.println(endDate);
System.out.println(timestamp);

我在 simpledateformat 中做错了吗?“MMM dd yyyy hh:mmaa”?

标签: javadatejava-7

解决方案


输入日期包含一个英文单词。您必须提供语言环境:

SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy hh:mmaa", Locale.ENGLISH);

推荐阅读