【问题标题】:Android SimpleDateFormat Unparsable DateAndroid SimpleDateFormat 无法解析的日期
【发布时间】:2017-02-28 23:09:49
【问题描述】:

我得到了这个日期字符串,例如:

Wed, 19 Oct 2016 12:00 PM CEST

现在我正在尝试借助 SimpleDateFormat 将其转换为日历

SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy hh:m a zzz", Locale.US);

当我尝试解析它时,我收到以下错误:

Unparseable date: "Wed, 19 Oct 2016 12:00 PM CEST" (at offset 26)

感谢每一个帮助!

编辑:

完整解析代码:

@Override
public WeatherData parseCurrentWeatherData(String jsonString) {

    WeatherData weatherData = new WeatherData();

    try {
        JSONObject obj = new JSONObject(jsonString);

        JSONObject mainObj = obj.getJSONObject("query").getJSONObject("results").getJSONObject("channel");

        JSONObject condition = mainObj.getJSONObject("item").getJSONObject("condition");

        Calendar cal = new GregorianCalendar();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy hh:m a z", Locale.US);
        cal.setTime(sdf.parse(condition.getString("date")));

        weatherData.setCalendar(cal);

    } catch(JSONException | ParseException ex) {
        Log.e("DataFetcher", ex.getLocalizedMessage());
    }

    return weatherData;
}

解决方案:

Android 似乎无法解析某些时区。感谢@Burhanuddin Rashid 提供的这种方法。

String strDate = condition.getString("date").replace("CEST", "GMT+0200");

这里的解决方案:Unparseable date: "Fri Oct 10 23:11:07 IST 2014" (at offset 20)

【问题讨论】:

  • 您的代码运行良好。
  • 但是为什么我的环境会出现解析错误呢?
  • 你能发布你的完整解析代码吗?
  • 我更新了我的问题@0riginal
  • 试试打印 condition.getString("date") 来检查你是否得到了正确的字符串

标签: java android simpledateformat parse-error


【解决方案1】:

请像这样在其中添加额外的 d:

    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy hh:m a zzz", Locale.US);
    sdf.setLenient(true);

【讨论】:

  • 尝试设置这个sdf.setLenient(true);
  • 尝试从 "EEE, dd MMM yyyy hh:m a zzz" 和 condition.getString("date") 中删除逗号 (,) 替换逗号 (,) ,而不是像这样的 condition.getString("date").replace(",","")
  • 仍然收到错误“无法解析的日期:“Wed 19 Oct 2016 01:00 PM CEST”(偏移量 25)”
  • 我认为这可能与“CEST”有关,因为它总是在 CEST 的偏移位置抛出错误?
  • 它似乎是 IST 问题,您可以参考它可能会有所帮助:stackoverflow.com/questions/27375489/…
【解决方案2】:
 public static void main(String[] args) throws ParseException {
    String dateString = "Wed, 19 Oct 2016 12:00 PM CEST";
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy hh:m a zzz", Locale.US);
    Date date = sdf.parse(dateString);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    System.out.println(calendar);
  }

同样的事情对我有用。

确保所有导入正确

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

【讨论】:

    【解决方案3】:

    您的 condition.getString("date") 和“SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy hh:m a z", Locale.US);" 中的格式不匹配。

    【讨论】:

    • 这是@Çağatay Karslı
    猜你喜欢
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多