Java ParseException while attempting String to Date parsing

 ̄綄美尐妖づ 提交于 2019-12-01 20:43:22
Rob

You could try:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = dateString.replace("Z", "GMT+00:00");
Date date = dateFormat.parse(dateString);

The above code should correctly handle the case where a timezone is specified in the date. As Z represents the UTC/GMT timezone it is replaced by GMT so the SimpleDateFormat can interpret it correctly (i would love to know a cleaner way of handling this bit if anyone knows one).

Try,

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Paul Jackson

This pattern should parse the date you provide: "yyyy-MM-dd'T'HH:mm:ss'Z'".
If you want to use SimpleDateFormat and you have a limited number of variations, you can create separate formatters for each pattern and chain them:

Date date = formatter1.parse(info.AiringTime);
if (date == null)
{
  date = formatter2.parse(info.AiringTime);
  if (date == null)
  {
    date = formatter2.parse(info.AiringTime);
    if (date == null)
    {
      date = formatter3.parse(info.AiringTime);
    }
  }
}

or put them in a list and iterate until non-null or no more formatters.
If you have too many patterns for this to be practical, you can parse it yourself or try one of these libraries.

This worked for me

    SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
    SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
    String viewFriendlyDate = "";
    try {
        Date date = isoDateFormat.parse(timestamp);
        viewFriendlyDate = viewFriendlyDateFormat.format(date);

    } catch (ParseException e) {
        e.printStackTrace();
    }
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try { 
    Date date = isoDateFormat.parse(timestamp);
    viewFriendlyDate = viewFriendlyDateFormat.format(date);

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