首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XMLGregorianCalendar到LocalDateTime

XMLGregorianCalendar到LocalDateTime
EN

Code Review用户
提问于 2019-03-04 16:03:41
回答 1查看 15.9K关注 0票数 5

从一些生成的代码中,我得到了一个javax.xml.datatype.XMLGregorianCalendar,我希望将它转换为没有任何区域偏移(UTC)的LocalDateTime

我的当前代码实现了它,但我认为必须能够以一种更优雅(更短)的方式来缓存同样的缓存。

代码语言:javascript
复制
    public static LocalDateTime xmlGregorianCalendar2LocalDateTime(XMLGregorianCalendar xgc) {
        // fix the time to UTC:
        final int offsetSeconds = xgc.toGregorianCalendar().toZonedDateTime().getOffset().getTotalSeconds();
        final LocalDateTime localDateTime = xgc.toGregorianCalendar().toZonedDateTime().toLocalDateTime(); // this simply ignores the timeZone
        return localDateTime.minusSeconds(offsetSeconds); // ajust according to the time-zone offet
    }
EN

回答 1

Code Review用户

回答已采纳

发布于 2019-03-07 13:37:34

类似于:

代码语言:javascript
复制
xgc.toGregorianCalendar().toZonedDateTime().toLocalDateTime() ?

如果您不想窃取区域信息,而是在UTC获取本地时间:

代码语言:javascript
复制
ZonedDateTime utcZoned = xgc.toGregorianCalendar().toZonedDateTime().withZoneSameInstant(ZoneId.of("UTC"));
LocalDateTime ldt = utcZoned.toLocalDateTime();

这个答案来自编写了java.time规范并实现它们的人--顺便说一句:https://stackoverflow.com/questions/29767084/convert-between-localdate-and-xmlgregoriancalendar

票数 9
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/214711

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档