You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中MongoDB聚合$dateToString如何指定时区?

在Java Spring Boot中为MongoDB聚合管道的$dateToString添加时区配置

需求目标

需要构建如下MongoDB聚合管道,为$dateToString指定Europe/Zurich时区:

"pipeline": [
  {
    "$project": {
      "productType": 1,
      "created": 1,
      "date": {
        "$dateToString": {
          "timezone": "Europe/Zurich",
          "format": "%Y.%m.%d",
          "date": "$created"
        }
      }
    }
  }
]

现有代码问题

当前实现能生成基础的聚合管道,但缺少时区配置:

Aggregation agg = newAggregation(
        project("productType", "created")
                .andExpression("created").dateAsFormattedString("%Y.%m.%d").as("date")
);

修改后的实现代码

可以通过两种方式为$dateToString添加时区配置:

方式一:使用重载的dateAsFormattedString方法

Spring Data MongoDB提供了带时区参数的重载方法,直接传入时区标识符即可:

Aggregation agg = newAggregation(
    project("productType", "created")
        .and("created")
        .dateAsFormattedString("%Y.%m.%d", "Europe/Zurich")
        .as("date")
);

方式二:手动构建$dateToString表达式

如果需要更贴近原始MongoDB语法,可通过andExpression直接编写完整的表达式:

Aggregation agg = newAggregation(
    project("productType", "created")
        .andExpression("{$dateToString: {timezone: 'Europe/Zurich', format: '%Y.%m.%d', date: '$created'}}")
        .as("date")
);

预期结果

修改后执行聚合,将得到符合时区转换的结果:

_id: "def166b4-967d-45ae-8b1c-1f05f8a1fc20"
productType: "car"
created: 2019-04-13T23:23:42.617+00:00
date: "2019.04.14"

内容的提问来源于stack exchange,提问作者user1350889

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 07:35:20