简体   繁体   English

如何在NodeJS,Mongoose和TypeScript中使用日期和时间?

[英]How to work with Date and Time in NodeJS, Mongoose and TypeScript?

I come from the java world and I'm starting in NodeJS. 我来自Java世界,现在开始使用NodeJS。 I'm having a hard time understanding how to work with dates and times in NodeJS. 我很难理解如何在NodeJS中使用日期和时间。

Only dates and only hours. 只有日期,只有小时。

Here is an example: 这是一个例子:

export interface teste extends mongoose.Document {
    description: string,
    dateTest: ????,
    openingTime: ????,
    finalTime: ????,
    dateTimeRecord: ????
}

const testeSchema = new mongoose.Schema({
    description:{
        type: String,
        required: true,
        maxlength: 200,
        minlength: 3
    },
    dateTest:{
        type: ?????,
        required: true
    },
    openingTime:{
        type: ?????,
        required: true
    },
    finalTime:{
        type: ?????,
        required: true
    },
    dateTimeRecord:{
        type: ?????,
        required: true
    }
}

export const Teste = mongoose.model<Teste>('Teste', testeSchema)

In all the places I left ????? 在所有我离开的地方 I don't know what to put. 我不知道该放什么。

  • In the dateTest I need to record only dates, without the hours. 在dateTest中,我只需要记录日期,而不需要记录小时数。
  • In the openingTime and finalTime I need to store only hours, no dates. 在openingTime和finalTime中,我只需要存储小时,没有日期。
  • In the dateTimeRecord I need to store the moment that something happened (date and time). 在dateTimeRecord中,我需要存储发生事件的时间(日期和时间)。

How to do this? 这个怎么做?

Mongoose has a Date type. 猫鼬具有Date类型。 (Docs here) Replace the ??? (此处为文档)替换??? with Date and you should be all set. Date ,你应该被设置。

in Mongoose you have a type of Date you can set a default date (Actually it uses ISODate) you can code it like this 在猫鼬中,您可以使用日期类型来设置默认日期(实际上它使用ISODate),您可以像这样编码

const testeSchema = new mongoose.Schema({
    description:{
        type: String,
        required: true,
        maxlength: 200,
        minlength: 3
    },
    dateTest:{
        type: Date,
        default:Date.now // this sets the default date time stamp using proper ISODate format
        required: true
    },
    openingTime:{
        type: Date,
        required: true
    },
    finalTime:{
        type: Date,
        required: true
    },
    dateTimeRecord:{
        type: Date,
        required: true
    }
}

you can read more in the mongoose documentation here 您可以在此处的猫鼬文档中了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM