2

我有这种格式的 DateTime'2020-11-08T13:05:46.000-07:00'并尝试将其设置为XMLGregorianCalendar. 它会自动转换为2020-11-08T20:05:46.000+0000.

无论如何将其保存为UTC?

4

2 回答 2

3

tl;博士

OffsetDateTime
.parse( "2020-11-08T13:05:46.000-07:00" )
.toInstant() 

java.time

XMLGregorianCalendar是一个遗留类,几年前被ZonedDateTime.

您的输入没有时区,只有与 UTC 的偏移量。所以将该字符串解析为OffsetDateTime.

OffsetDateTime odt = OffsetDateTime.parse( "2020-11-08T13:05:46.000-07:00" ) ;

调整到 UTC(零时分秒的偏移量)的最简单方法是提取Instant.

Instant instant = odt.toInstant() ;
于 2020-11-19T20:03:06.667 回答
1

你可以这样做:

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class Main {
    public static void main(String[] args) throws DatatypeConfigurationException {
        String givenDateTimeString = "2020-11-08T13:05:46.000-07:00";
        XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance()
                .newXMLGregorianCalendar(givenDateTimeString);
        System.out.println(xmlGregorianCalendar);
    }
}

输出:

2020-11-08T13:05:46.000-07:00

但是,我建议您切换到现代日期时间 API

使用现代日期时间 API:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String givenDateTimeString = "2020-11-08T13:05:46.000-07:00";
        OffsetDateTime odt = OffsetDateTime.parse(givenDateTimeString);
        // Default format i.e. OffsetDateTime#toString
        System.out.println(odt);

        // Custom format
        System.out.println(odt.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH)));

        // Convert it to date-time at UTC
        OffsetDateTime odtUTC = odt.withOffsetSameInstant(ZoneOffset.UTC);
        System.out.println(odtUTC);
        System.out.println(odtUTC.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH)));
    }
}

输出:

2020-11-08T13:05:46-07:00
2020-11-08T13:05:46.000-07:00
2020-11-08T20:05:46Z
2020-11-08T20:05:46.000Z

在Trail: Date Time了解有关现代日期时间 API 的更多信息。

于 2020-11-19T20:03:33.677 回答