栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

MongoDB的ZonedDateTime

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MongoDB的ZonedDateTime

看起来Spring支持所有Java时间转换器减去分区日期时间转换器。您可以如下注册一个。

@Beanpublic CustomConversions customConversions(){    List<Converter<?,?>> converters = new ArrayList<Converter<?,?>>();    converters.add(new DateToZonedDateTimeConverter());    converters.add(new ZonedDateTimeToDateConverter());    return new CustomConversions(converters);}@Beanpublic MongoTemplate getMongoTemplate() throws UnknownHostException {    MappingMongoConverter converter = new MappingMongoConverter( new DefaultDbRefResolver(getMongoDbFactory()), new MongoMappingContext());    converter.setCustomConversions(customConversions());    converter.afterPropertiesSet();    return new MongoTemplate(getMongoDbFactory(), converter);}class DateToZonedDateTimeConverter implements Converter<Date, ZonedDateTime> {     @Override     public ZonedDateTime convert(Date source) {   return source == null ? null : ofInstant(source.toInstant(), systemDefault());         }     }class ZonedDateTimeToDateConverter implements Converter<ZonedDateTime, Date> {    @Override    public Date convert(ZonedDateTime source) {  return source == null ? null : Date.from(source.toInstant());       }   }

另一种替代解决方案是仅使用ZonedDateTime并将其更改为日期,同时将其持久化到MongoDB中。您可以在获取时轻松地将其从日期改回分区日期时间。

以下是有助于转换的相关方法。

ZoneId zoneID = ZoneId.of("America/Chicago");

从ZonedDateTime到Java使用日期。

Instant instant = Instant.now();ZonedDateTime zonedDateTime = instant.atZone(zoneId);Date date = Date.from(zdt.toInstant());

从日期到ZonedDateTime

Instant instant = date.toInstant();ZonedDateTime zonedDateTime = instant.atZone(zoneId);

另一种选择是实现自定义编解码器以帮助进行转换。我已经在Mongo文档的筛选YearMonth中为YearMonth创建了一个。如果读者想为“区域日期时间”创建自定义编解码器,我将把它留给读者练习。

您可以将以下库用于基于编解码器的方法。

https://github.com/ylemoigne/mongo-jackson-
prec



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/496896.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号