简体   繁体   English

如何将字符串转换为 xml 公历日期 java

[英]How to Convert string to xml gregorian calendar date java

I am trying to convert String to gregoriancalendar date, it unable to convert.我正在尝试将 String 转换为 gregoriancalendar 日期,但无法转换。 because, the string has different format.因为,字符串具有不同的格式。 like ' 2015-05-22T16:28:40.317-04:00 '.像' 2015-05-22T16:28:40.317-04:00 '。 I have seen some of the other examples, but they are not in this time format.我看过其他一些例子,但它们不是这种时间格式。

I am using something like below:我正在使用类似下面的东西:

GregorianCalendar cal = new GregorianCalendar();
         cal.setTime(new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss-SS:zz").parse(sampleDate));
         XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar( cal);

I even tried like this too:我什至也这样尝试过:

gregory.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(sampleDate));

If you check SimpleDateFormat doc, you will see that there's no T in the format pattern.如果您查看SimpleDateFormat文档,您将看到格式模式中没有T In order to escape non-pattern characters, wrap them around single quotes ' as shown in this example (taken from the docs):为了转义非模式字符,将它们用单引号'括起来,如本例所示(取自文档):

"hh 'o''clock' a, zzzz" -> 12 o'clock PM, Pacific Daylight Time

I think the proper format should be this:我认为正确的格式应该是这样的:

String format = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
//                         ^-^-----check these
// don't pay attention to the smiley generated above, they're arrows ;)
GregorianCalendar cal = new GregorianCalendar();
     cal.setTime(new SimpleDateFormat(format).parse(sampleDate));
     XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar( cal);

This works as well这也有效

XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2015-05-22T16:28:40.317-04:00");
GregorianCalendar gregorianCalendar = xmlGregorianCalendar.toGregorianCalendar();
   try {
      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss-SS:zz");
      //dateFormat.setTimeZone(TimeZone.getTimeZone());
      Date inputDate = dateFormat.parse(inputDatetime);

      GregorianCalendar c = new GregorianCalendar();
      c.setTime(inputDate);

      XMLGregorianCalendar outputDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);

      return outputDate;

    } catch (ParseException | DatatypeConfigurationException e) {
      log.error("exception: {}", e.getMessage());
      return null;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM