Java dateFormat无法解析的日期异常

时间:2016-04-13 10:23:19

标签: java

我在将json对象中收到的日期转换为所需格式时遇到问题。我从后端得到的日期是Apr-13, Wednesday, 04:06:00 PM。这就是我所做的。

String refreshDateString = jobj.optString("refresh_date").toString();
SimpleDateFormat parseFormat = new SimpleDateFormat("MMM-dd, EEEE  hh:mm:ss a");
Date refreshDate = parseFormat.parse(refreshDateString.replaceAll("\\p{Cntrl}", ""));
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM dd, E, hh:mm a");

我也尝试使用单个E而不是EEEE。对我错在哪里的任何输入?非常感谢!

3 个答案:

答案 0 :(得分:1)

您在一周中的一天名称后错过了,,并且您应该使用E代替EEEE,请使用此格式

DateFormat parseFormat = new SimpleDateFormat("MMM-dd, E, hh:mm:ss a");

如果你在一周之后的名字之后没有,; EEEEhh EEEE hh:mm:ss之间有额外的空格。请改用

DateFormat parseFormat = new SimpleDateFormat("MMM-dd, E hh:mm:ss a");

答案 1 :(得分:0)

您的模式中缺少额外的空格和逗号。但重要的是,如果您的系统使用的语言与您收到的日期不同,则为Locale:

SimpleDateFormat parseFormat = new SimpleDateFormat("MMM-dd, EEEE, hh:mm:ss a", Locale.US);

就我而言,由于我的机器是意大利语,没有语言环境,我将永远无法解析给定的日期。

答案 2 :(得分:0)

另外,我建议您使用JodaTime库或Java 8中包含的最新版本的Date API(实际上是JodaTime的复制和粘贴)。因为使用日期更好。因此,要解析给定格式的字符串,将看起来像

String string = "Apr-13, Wednesday, 04:06:00 PM";
DateTimeFormatter formatter = DateTimeFormat.forPattern("MMM-dd, E, hh:mm:ss a");
DateTime dt = formatter.parseDateTime(string);

如果你的代码中有很多日期转换等,那肯定是必须的。