java日期格式与xquery xs:date格式不兼容,如何解决?

时间:2020-03-06 15:04:19  来源:igfitidea点击:

在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想要的方式。

谢谢!

解决方案

试试这个:

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

好的,链接到论坛的帖子DID帮助,谢谢。但是,我确实找到了一个更简单的解决方案,其中包括以下内容:

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)

好吧,我确实遇到了一个问题,在我看来(似乎是错误的),没有任何方法可以将DateUtils(来自apache commons lang)创建的ISO字符串和ISO字符串转换为日期!
IE。 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());  
}

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

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