Java XMLGregorianCalendar 类型的 Joda 日期时间格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21294961/
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-08-13 07:56:48  来源:igfitidea点击:

Joda DateTime Format for XMLGregorianCalendar Type

javaxmljaxb

提问by c12

I'm using JAXB 2.2.8-b01 impl and I have a schema which has a xs:date element which creates a XMLGregorianCalendar instance. I'm trying to get a Joda-TimeDateTimetimestamp format but since I have to have a XMLGregorianCalendar instance, I'm not sure its possible. Any ideas?

我正在使用 JAXB 2.2.8-b01 impl 并且我有一个架构,它有一个 xs:date 元素,它创建一个 XMLGregorianCalendar 实例。我正在尝试获取Joda-Time DateTime时间戳格式,但由于我必须有一个 XMLGregorianCalendar 实例,我不确定它是否可能。有任何想法吗?

Schema XSD:

架构 XSD:

<xs:element type="xs:date" name="date-archived" minOccurs="0" maxOccurs="1" nillable="false"/>

JAXB Generated Property:

JAXB 生成的属性:

@XmlSchemaType(name = "date")
protected XMLGregorianCalendar date;

XML Conversion Class:

XML 转换类:

//java.util.Date being passed


private XMLGregorianCalendar converToGregorianCal(Date date) {
    DatatypeFactory df = null;
    try {
        df = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        LOG.error("error getting DatatypeFactory instance " + e.getMessage()); 
    }
    if (date == null) {
        return null;
    } else {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(date.getTime());
        return df.newXMLGregorianCalendar(gc);
    }
}

回答by Basil Bourque

Your question is not clear.

你的问题不清楚。

DateTime?

约会时间?

If you have a java.util.Date, you can easily convert that to a Joda-Time DateTime:

如果您有 java.util.Date,您可以轻松地将其转换为 Joda-Time DateTime:

  1. Pass the Date instance to constructor of a DateTime.
  2. Pass a DateTimeZone instance to the same constructor.
  1. 将 Date 实例传递给 DateTime 的构造函数。
  2. 将 DateTimeZone 实例传递给同一个构造函数。

While a java.util.Datehas no time zone assigned (it represents UTC/GMT, without any time zone offset), an org.joda.time.DateTimedoes indeed know its own time zone. If you want your DateTime to have UTC/GMT instead of a specific time zone, use the built-in constant DateTimeZone.UTC.

虽然 ajava.util.Date没有分配时区(它代表 UTC/GMT,没有任何时区偏移),但 anorg.joda.time.DateTime确实知道自己的时区。如果您希望 DateTime 具有 UTC/GMT 而不是特定时区,请使用内置常量DateTimeZone.UTC

java.util.Date someDate = new java.util.Date();
DateTime dateTime = new DateTime( someDate, DateTimeZone.UTC );

// Or, a specific time zone.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTimeParis = new DateTime( someDate, timeZone );

Dump to console…

转储到控制台...

System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeParis: " + dateTimeParis );

When run…

运行时…

dateTime: 2014-01-22T22:39:03.996Z
dateTimeParis: 2014-01-22T23:39:03.996+01:00

Passing the Date instance, it's just that easy. You could extract from the Date instance it's number of milliseconds since the UnixEpoch, and pass that longnumber to DateTime. But no need, as the DateTime class is willing to that work.

传递 Date 实例,就是这么简单。您可以从 Date 实例中提取自Unix Epoch以来的毫秒数,并将该long数字传递给 DateTime。但没有必要,因为 DateTime 类愿意进行这项工作。

String?

细绳?

Or by “timestamp format” did you mean you want an ISO 8601formatted string like this: 2014-01-19T12:38.301Z? That string format is the default for a DateTime's toStringmethod.

或者说“时间戳格式”,你的意思是你想要一个像这样的ISO 8601格式的字符串:2014-01-19T12:38.301Z?该字符串格式是 DateTimetoString方法的默认格式。

String isoString = new DateTime( someDate, DateTimeZone.UTC ).toString();

回答by Murillo Maia

Be very careful with JodaTime, the lib don't use the timezone tables of java.

使用 JodaTime 时要非常小心,lib 不使用 java 的时区表。

public class XMLCalendarToDateTime {

    private static DatatypeFactory df = null;
    static {
        try {
            df = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException dce) {
            throw new IllegalStateException(
                "Exception while obtaining DatatypeFactory instance", dce);
        }
    }  

    private static XMLGregorianCalendar converToGregorianCal(DateTime dateTime) {
        if (dateTime == null) {
            return null;
        } else {
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTimeInMillis(dateTime.getMillis());
            return df.newXMLGregorianCalendar(gc);
        }
    }

    private static DateTime convertToDateTime(XMLGregorianCalendar xmlGregorianCalendar){
         if (xmlGregorianCalendar == null) {
                return null;
            } else {
                return new DateTime(xmlGregorianCalendar.toGregorianCalendar().getTime());
            }
    }

    public static void main(String[] args) {

        final DateTime dateTime = new DateTime(2014,1,1,1,1);

        System.out.println("date = " + dateTime.toString());

        final XMLGregorianCalendar xmlGregorianCalendar = converToGregorianCal(dateTime);

        System.out.println("xmlGregorianCalendar = " + xmlGregorianCalendar);

        final DateTime dateTimeConverted = convertToDateTime(xmlGregorianCalendar);

        System.out.println("dateTimeConverted = "  + dateTimeConverted);

    }
}

回答by bdoughan

Below is how you can have xs:datecorrespond to Joda-Time DateTimebeing generated into the class model.

下面是如何xs:date将 Joda-TimeDateTime生成到类模型中。

XML Schema

XML 架构

Below is an XML Schema with two elements of type xs:date:

下面是一个带有两个 type 元素的 XML 模式xs:date

<?xml version="1.0" encoding="UTF-8"?>
<schema 
    xmlns="http://www.w3.org/2001/XMLSchema" 
    targetNamespace="http://www.example.org/schema" 
    xmlns:tns="http://www.example.org/schema" 
    elementFormDefault="qualified">

    <element name="root">
        <complexType>
            <sequence>
                <element name="foo" type="date"/>
                <element name="bar" type="date"/>
            </sequence>
        </complexType>
    </element>

</schema>

Binding xs:dateto Joda-Time DateTime

绑定xs:date到 Joda-TimeDateTime

An external binding document can be used to customize the class generation, below is what you would need to do to generate Joda-Time DateTimefor xs:date. The binding document is referenced using the -bflag to XJC.

外部绑定文档可用于自定义类生成,以下是生成 Joda-Time DateTimefor xs:date. 使用-bXJC的标志引用绑定文档。

xjc -b binding.xml schema.xsd

Bind All Instances

绑定所有实例

<?xml version="1.0" encoding="UTF-8"?>
<jxb:bindings version="2.1"
              xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
              xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <jxb:globalBindings>
        <!-- use JODA-Time DateTime for xs:date -->
        <jxb:javaType name="org.joda.time.DateTime" xmlType="xs:date"
            parseMethod="com.example.MyConverter.parseDate"
            printMethod="com.example.MyConverter.printDate"/>
    </jxb:globalBindings>        
</jxb:bindings>

Bind One Instance

绑定一个实例

The binding file below will cause the fooelement to use DateTimebut not the barelement.

下面的绑定文件将导致使用foo元素DateTime但不使用bar元素。

<?xml version="1.0" encoding="UTF-8"?>
<jxb:bindings version="2.1" xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <jxb:bindings schemaLocation="schema.xsd">
        <jxb:bindings node="//xs:element[@name='foo']">
            <jxb:property>
                <jxb:baseType>
                    <jxb:javaType 
                       name="org.joda.time.DateTime" 
                       parseMethod="com.example.MyConverter.parseDate" 
                       printMethod="com.example.MyConverter.printDate" />
                </jxb:baseType>
            </jxb:property>
        </jxb:bindings>
    </jxb:bindings>
</jxb:bindings>

com.example.MyConverter

com.example.MyConverter

This is where you put your logic to convert a Stringto from DateTime:

这是您将逻辑转换String为 from 的地方DateTime

import org.joda.time.DateTime;

public class MyConverter {

    public static String printDate(DateTime value) {
        // TODO - Conversion Logic
    }

    public static DateTime parseDate(String value) {
       // TODO - Conversion Logic
    }

}

For More Information

想要查询更多的信息

回答by thomas.mc.work

This is a short way:

这是一个简短的方法:

public DateTime convert(final XMLGregorianCalendar xmlgc) {
    return new DateTime(xmlgc.toGregorianCalendar().getTime());
}

回答by flurdy

Unclear from the question but if you want XMLGregorianCalendarfrom JodaTime DateTime, then this is possible:

从问题中不清楚,但如果你想要XMLGregorianCalendarJodaTime DateTime,那么这是可能的:

final GregorianCalendar calendar = new GregorianCalendar(dateTime.getZone().toTimeZone());
calendar.setTimeInMillis(dateTime.getMillis());
return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);

回答by Sanjay Bharwani

We have faced this and after spending time with formatters found a simplest solution

我们遇到了这个问题,在与格式化程序一起花费时间后找到了一个最简单的解决方案

String sf = xmlGregDate.toString()
DateTime dateTime = DateTime.parse(sf)

This was a life savour.

这是一种生活品味。