java日期格式与xquery xs:日期格式不兼容,如何修复?

在java中,当使用带有模式的SimpleDateFormat时:

yyyy-MM-dd'T'HH:mm:ss.SSSZ 

日期输出为:

 "2002-02-01T18:18:42.703-0700" 

在xquery中,当使用xs:dateTime函数时,它会给出错误:

 "Invalid lexical value [err:FORG0001]" 

与上述日期。 为了使xquery正确解析,日期需要如下所示:

 "2002-02-01T18:18:42.703-07:00" - node the ':' 3rd position from end of string 

它基于ISO 8601,而Java日期则基于RFC 822标准。

我希望能够在Java中轻松指定时区,以便输出xquery想要的方式。

谢谢!

好的,链接到论坛postDID帮助,谢谢。 然而,我确实找到了一个更简单的解决方案,我在下面包括:

1)使用Apache commons.lang java库
2)使用以下java代码:

 //NOTE: ZZ on end is not compatible with jdk, but allows for formatting //dates like so (note the : 3rd from last spot, which is iso8601 standard): //date=2008-10-03T10:29:40.046-04:00 private static final String DATE_FORMAT_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"; DateFormatUtils.format(new Date(), DATE_FORMAT_8601) 

关于commons.lang.java的好发现! 您甚至可以通过执行以下操作来避免创建自己的格式字符串:

 DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(new Date()); 

好吧,我确实遇到了一个问题 – 它似乎没有(我可能是错的)有任何方式转换和ISO字符串DateUtils(来自apache commons lang)创建,回到约会!
即。 apache commons会按照我想要的方式格式化它,但不会再将它转换回日期

所以,我改用了JodaTime,它基于ISO8601更容易 – 这里是代码:

 public static void main(String[] args) { Date date = new Date(); DateTime dateTime = new DateTime(date); DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); String dateString = fmt.print(dateTime); System.out.println("dateString=" + dateString); DateTime dt = fmt.parseDateTime(dateString); System.out.println("converted date=" + dt.toDate()); } 

尝试这个:

 static public String formatISO8601(Calendar cal) { MessageFormat format = new MessageFormat("{0,time}{1,number,+00;-00}:{2,number,00}"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); df.setTimeZone(cal.getTimeZone()); format.setFormat(0, df); long zoneOff = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET) / 60000L; int zoneHrs = (int) (zoneOff / 60L); int zoneMins = (int) (zoneOff % 60L); if (zoneMins < 0) zoneMins = -zoneMins; return (format.format(new Object[] { cal.getTime(), new Integer(zoneHrs), new Integer(zoneMins) })); }