在默认日期和时间中存储错误的时区
Store wrong timezone in default date and time
我正在尝试使用 mongoose 和 Node.JS 来存储默认日期和时间,但不知何故,它在数据库中存储了不同的时区值。我正在使用“MongoDB Atlas Database”作为数据库服务器,并且还参考 this. I have also tried 配置了默认时区以更改时区,并且还尝试了 "moment-timezone.js",但没有得到任何运气。
我只想使用印度标准时间格式存储默认日期和时间。
以下是我的架构代码。
const testSchema = new mongoose.Schema({
from: String,
to: String,
amount: Number,
message: {
type: String,
default: ""
},
creationdate: {
type: Date,
default: Date.now
}
});
请帮我解决这个问题。告诉我解决这个问题的最佳方法。
MongoDB 将 Date
fields 存储为自 Unix 纪元以来以毫秒为单位的 UTC 时间戳,这是一个 64 位整数(在 JS 中为 53 位)。这也是 Date.now()
的意思。根据设计,数据没有时区组件。
如果您需要日期对象的一致时区格式,请添加 virtual field returns 所需的时区调整字符串或日期对象。
const testSchema = new mongoose.Schema({
creationdate: {
type: Date,
default: Date.now
}
});
testSchema.virtual('formattedCreationDate').get(function() {
return this.creationdate.toLocaleString(); // or day.js/luxon
});
如果您需要用户或系统提供的时区以外的其他内容,请将数据存储在另一个字段中,并在 virtual
格式中使用该时区字段。
我正在尝试使用 mongoose 和 Node.JS 来存储默认日期和时间,但不知何故,它在数据库中存储了不同的时区值。我正在使用“MongoDB Atlas Database”作为数据库服务器,并且还参考 this. I have also tried
我只想使用印度标准时间格式存储默认日期和时间。
以下是我的架构代码。
const testSchema = new mongoose.Schema({
from: String,
to: String,
amount: Number,
message: {
type: String,
default: ""
},
creationdate: {
type: Date,
default: Date.now
}
});
请帮我解决这个问题。告诉我解决这个问题的最佳方法。
MongoDB 将 Date
fields 存储为自 Unix 纪元以来以毫秒为单位的 UTC 时间戳,这是一个 64 位整数(在 JS 中为 53 位)。这也是 Date.now()
的意思。根据设计,数据没有时区组件。
如果您需要日期对象的一致时区格式,请添加 virtual field returns 所需的时区调整字符串或日期对象。
const testSchema = new mongoose.Schema({
creationdate: {
type: Date,
default: Date.now
}
});
testSchema.virtual('formattedCreationDate').get(function() {
return this.creationdate.toLocaleString(); // or day.js/luxon
});
如果您需要用户或系统提供的时区以外的其他内容,请将数据存储在另一个字段中,并在 virtual
格式中使用该时区字段。