Carlos Vinicius
Carlos Vinicius

Reputation: 63

Store only time in Mongodb

I need to store in MongoDB just the time. The user types just the time, e.g. "05:20" as a string, and I need to convert and store this time.

Any tips?

I've been trying to use Date object, but with no success.

Upvotes: 6

Views: 11204

Answers (3)

réze
réze

Reputation: 1

expirationDate: {
    type: String,
    default: function () {
        let sessionTimer = new Date();
        sessionTimer.setHours(sessionTimer.getHours() + 1);
        return sessionTimer.toISOString();
    },

i stored it as a string, create a default function as the above which creates or stores the time in iso string format.........but note to get the best outcome make sure us use the date object to convert the default db query for the BEST COMPARISON e.g new Date(mongooseDate) - yourDate...and vice versa

Upvotes: 0

you can use moment.js library and store the time as number moment("1135","HHmm").format("HH:mm"); // equals 11:35 or moment("135","HHmm").format("HH:mm"); // equals 01:35

Upvotes: 0

Ilarion Halushka
Ilarion Halushka

Reputation: 2343

Basically you have two options:

  1. Save time in type: String

  2. Save date time in type: Date

But in second option you have to create Date object and set hours and minutes:

   const userInput = '05:20';
   const hours = userInput.slice(0, 2);
   const minutes = userInput.slice(3);

   const date = new Date(dateString);
   date.setHours(hours, minutes);

Upvotes: 12

Related Questions