Search code examples
node.jsangularmongodb

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.


Solution

  • 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);