Search code examples
node.jsmongodbdatemongooseutc

Date format in our Application


Can anyone tell me which is the right format to store date in my database.

Suppose if the client and the server are in the same region, we can use unix epoch timestamp or date string. But if the server is in US and the client is from Asia, I knew people saying UTC to auto convert date from the particular region. But I cannot store UTC in MongoDB via Node js, maybe i made it in the wrong way.

.currently I store "09-02-2021" for date and 1612837056077 timestamp. I also get the time from the front end.Also, I am not sure with the above things. Can someone explain the right way of using date and time in a real world application. If possible show me a quick demo in node js and mongoose

Thank you all :)


Solution

  • UTC is the way to go. I don't know what you mean by "But I cannot store UTC in MongoDB via Node js". Create your schema like so:

    const client_schema = new mongoose.Schema({
      ...
      ...
      date_created: {type: Date, default: Date.now},
      ...
      ...
    });
    

    And date_created will always be stored in UTC format. From UTC, you can convert it to any timezone. Here is just one example, using moment, of how to convert UTC to a Eastern Timezone:

    const d = moment(utc_date).utcOffset(moment(utc_date).tz("America/New_York").format('Z'), true).toDate();
    

    Note: moment is being phased out and is no longer recommended for new projects.