代码之家  ›  专栏  ›  技术社区  ›  JimB814

为什么Mongodb中的ISO日期提前一天显示?

  •  2
  • JimB814  · 技术社区  · 7 年前

    ...
    "date_of_birth" : ISODate("1920-01-02T00:00:00Z"),
    ...
    

       AuthorSchema
       .virtual('date_of_birth_update_format')
       .get(function(){
          // format in JavaScript date format (YYYY-MM-DD) to display in input type="date"
          return this.date_of_birth ? moment(this.date_of_birth).format('YYYY-MM-DD') : '';
       });
    

    从集合中检索并显示,它显示为前一天,如下所示:

    01/01/1920
    

    4 回复  |  直到 5 年前
        1
  •  1
  •   sidgate    7 年前

    mongo的日期始终以GMT为单位,您的服务器可能位于其他时区。格式化之前,需要将日期转换为GMT。

    var moment = require("moment-timezone")
    
    AuthorSchema.virtual('date_of_birth_update_format').get(function(){
     return this.date_of_birth ? moment(this.date_of_birth).tz('GMT').format('YYYY-MM-DD') : '';
    });
    
        2
  •  1
  •   Jon Wolski    7 年前

    Z 在ISO 8601格式中,表示“GMT”,即。 1920-01-02T00:00:00+0000 . 这一时刻将考虑您的时区。如果你在美国大陆,你的时区偏移是 -0400 -0800 .

    1920-01-02T00:00:00Z = 1920-01-01T6:00:00-0600 例如在太平洋标准时间。

        3
  •  0
  •   Vignesh    7 年前

        4
  •  0
  •   Dharman Aman Gojariya    3 年前

    这里也有同样的问题。我使用EJS显示从MongoDB数据库检索到的日期。我不确定问题是否出在EJS上,但我是这样解决的:

    我所要做的就是在前端将时区设置为GMT:

    date.toLocaleString("pt-BR", {timeZone:"GMT", day: "numeric", month: "numeric", year:"numeric"});