Why the error Unparseable date happened in Android?

家住魔仙堡 提交于 2021-02-11 04:50:12

问题


I am trying to convert the string to Date like the following:

val inputFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.getDefault())
val s = "Mon, 14 Oct 2019 07:10:28"
val time = inputFormat.parse(s)
Log.d("HttpTools", "time server:$time")

But it show the error

java.text.ParseException: Unparseable date: "Mon, 14 Oct 2019 07:10:28"

Did I missing something ? Thanks in advance.


回答1:


Use this format: EEE, dd MMM yyyy hh:mm:ss




回答2:


The format is wrong.

According to the documentation, your format should be

EEE, dd MMM yyyy HH:mm:ss

Note that:

  • DDD becomes EEE, as you need the 3 letter day name

  • hh becomes HH, as you need the day hour (0-23). hh will work only if you use am/pm




回答3:


If you are using the java-8 you can use the LocalDateTime and DateTimeFormatter

String text = "Mon, 14 Oct 2019 07:10:28";

DateTimeFormatter format = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss", Locale.getDefault());

LocalDateTime dateTime = LocalDateTime.parse(text, format);

System.out.println(dateTime);    // 2019-10-14T07:10:28



回答4:


You must use this format to get the day

EEE, dd MMM yyyy HH:mm:ss



回答5:


Had the same problem and the answer is just as @Meno Hochschild and others suggested in their comments, to not use Locale.getDefault() because you have english text (the name of the month) in your string so if your local from Locale.getDefault() don't return English the parsing fails with exact this exception even if the pattern is right. It's simply because the locale isn't matching the input string language. In my case i had a similar string to yours just the date was different and was using Locale.getDefault() which returned German in my case but the month name in my date string was written in english and so i always received this exception. If you know that the incoming date strings are always localized in english, you can simply set Locale.ENGLISH as the second param of SimpleDateFormat.



来源:https://stackoverflow.com/questions/58371959/why-the-error-unparseable-date-happened-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!