Java ParseException while attempting String to Date parsing

前端 未结 5 1046
生来不讨喜
生来不讨喜 2021-01-20 08:32

I\'m having a hard time Parsing/Formatting a Date string received back from a web service. I\'ve attempted multiple approaches, but with no luck.

Sample Dat

相关标签:
5条回答
  • 2021-01-20 09:02
    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(); 
    } 
    
    0 讨论(0)
  • 2021-01-20 09:06

    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).

    0 讨论(0)
  • 2021-01-20 09:07

    Try,

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    
    0 讨论(0)
  • 2021-01-20 09:08

    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();
        }
    
    0 讨论(0)
  • 2021-01-20 09:26

    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.

    0 讨论(0)
提交回复
热议问题