Reputation: 63
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
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
Reputation: 54
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
Reputation: 2343
Basically you have two options:
Save time in type: String
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