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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32129093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:41:56  来源:igfitidea点击:

How to Convert string to xml gregorian calendar date java

javastringdatetimegregorian-calendar

提问by Dave

I am trying to convert String to gregoriancalendar date, it unable to convert. because, the string has different format. like '2015-05-22T16:28:40.317-04:00'. I have seen some of the other examples, but they are not in this time format.

我正在尝试将 String 转换为 gregoriancalendar 日期,但无法转换。因为,字符串具有不同的格式。像' 2015-05-22T16:28:40.317-04:00'。我看过其他一些例子,但它们不是这种时间格式。

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

回答by Luiggi Mendoza

If you check SimpleDateFormatdoc, you will see that there's no Tin the format pattern. In order to escape non-pattern characters, wrap them around single quotes 'as shown in this example (taken from the docs):

如果您检查SimpleDateFormatdoc,您会看到T格式模式中没有。为了转义非模式字符,将它们用单引号括起来',如本例所示(取自文档):

"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);

回答by phoenixSid

This works as well

这也有效

XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2015-05-22T16:28:40.317-04:00");
GregorianCalendar gregorianCalendar = xmlGregorianCalendar.toGregorianCalendar();

回答by Vicky

   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;
    }