2011-12-13 58 views
2

变换字符串转换日期我得到这个日期从SOAP消息的字符串使用日期格式

"2009-12-02T12:58:38.415+01:00" 

大多数我能我能识别和主题是

与此格式yyyy-MM-dd ? hh:mm:ss.????

玩变化

我试过不同的组合使用SSS T Z Z而不是'?“

DateFormat df = new SimpleDateFormat("... various formats ..."); 
System.out.println(df.parse("2009-12-02T12:58:38.415+01:00")); 

但没有成功。

有什么想法?

谢谢

回答

4

您必须更改时区的一部分。试试这个:

String a = "2009-12-02T12:58:38.415+01:00"; 
    a = a.replaceFirst(":(?=\\d+$)", ""); 
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
    System.out.println(df.parse(a)); 
+0

谢谢,现在我试着理解正则表达式:) – Cris

+1

@Cris它只是删除最后一个冒号 – Kent

+0

你有老鹰的眼睛去发现最后一个“:”:) – Cris

1

我不认为这是可能的使用标准的Java日期格式。 使用joda-time这是可以做到使用下面的代码:

DateTimeFormatterBuilder b = new DateTimeFormatterBuilder() 
      .appendYear(4, 4).appendLiteral('-').appendMonthOfYear(2).appendLiteral('-').appendDayOfMonth(2) 
      .appendLiteral('T') 
      .appendHourOfDay(2).appendLiteral(':').appendMinuteOfHour(2).appendLiteral(':').appendSecondOfMinute(2) 
      .appendLiteral('.').appendMillisOfSecond(3).appendTimeZoneOffset(null, true, 2, 2); 
    DateTimeFormatter dateTimeParser = b.toFormatter(); 
    System.out.println(dateTimeParser.parseDateTime("2009-12-02T12:58:38.415+01:00")); 
+0

不,它不是。看看时区的一部分。 – Kent

+0

尝试在简单的主....线程“主”的异常java.text.ParseException:Unparseable日期:“2009-12-02T12:58:38.415 + 01:00” – Cris

+0

你是对的肯特,完全错过了冒号... –

1

请尝试以下操作。

String date = "2009-12-02T12:58:38.415+01:00"; 
     int lastIndexOf = date.lastIndexOf(":"); 
     if(lastIndexOf>=0){ 
     date = date.substring(0,lastIndexOf)+date.substring(lastIndexOf+1); 
     } 
     System.out.println("~~~~~~date~~~~~"+date); 
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSZ"); 
     try { 
      sdf.parse(date); 
      System.out.println("....date..."+date); 
     } catch (ParseException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     }