我在尝试解析时间字符串 02:22 p.m.
时遇到解析异常。
我有以下转换函数:
public static long convertdatetotimestamp(String datestring, String newdateformat, String olddateformat){
SimpleDateFormat originalFormat = new SimpleDateFormat(olddateformat,Locale.ROOT);
SimpleDateFormat targetFormat = new SimpleDateFormat(newdateformat,Locale.ROOT);
Date date = null;
try {
date = originalFormat.parse(datestring);
String formattedDate = targetFormat.format(date);
Date parsedDate = targetFormat.parse(formattedDate);
long nowMilliseconds = parsedDate.getTime();
return nowMilliseconds;
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
该方法在另一个时间格式为 "02:22 p.m."
的 Activity 中调用。 olddateformat
和 newdateformat
相同:hh:mm a
。
它导致日志中出现以下错误:
java.text.ParseException: Unparseable date: "02:22 p.m." (at offset 6)
如何解决这个问题?时间就是上面提到的格式。
最佳答案
碰巧上午和下午。在盖尔语言环境中就是这样称呼的。至少在我的 Java 8 上是这样。我不确定(所有)Android 手机是否会出现这种情况,但您可以用它做一些实验。
String datestring = "02:22 p.m.";
Locale parseLocale = Locale.forLanguageTag("ga");
DateTimeFormatter originalFormat = DateTimeFormatter.ofPattern("hh:mm a", parseLocale);
System.out.println(LocalTime.parse(datestring, originalFormat));
这打印
14:22
Hugo 如此热情而正确地推荐的是 his answer ,我使用的是现代 Java 日期和时间 API,因此上面的代码需要 ThreeTenABP。参见 How to use ThreeTenABP in Android Project .或者,您可能想使用其他已过时的 SimpleDateFormat
尝试相同的语言环境。
美国西类牙语语言环境在我的 Java 8 上显示相同的行为,因此您也可以尝试:Locale.forLanguageTag("es-US")
。
关于java - Android 上的时间解析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45237783/