Reputation: 151
I have a variable called workFrom that has time(hh:mm) as String at the FrontEnd(Angular JS). I would like to convert this to Date format before posting the data on to MongoDB with default date as 01/01/1970 and the time from whatever has been posted from workFrom. How do I do it?
Eg : workFrom : 11:40 should be converted to 01/01/1970 11:40 (according to the standard format of date used in MongoDB).
Thanks in advance
Upvotes: 2
Views: 31003
Reputation: 5519
Solution in vanila JS.
var input = '11:40';
var parts = input.split(':');
var minutes = parts[0]*60 +parts[1];
var inputDate = new Date(minutes * 60 * 1000);
console.log(inputDate);
Or use moment as wrote abhishekkannojia.
Upvotes: 2
Reputation: 303
With using moment (Which I recomend whenever you are dealing with date/time related problems):
let workFrom = "11:40";
let workFromMoment = moment(workFrom,'hh:mm')
let adjustedMoment = moment([1970,0,1]).hour(workFromMoment.hour()).minute(workFromMoment.minute())
let dateString = adjustedMoment.format('D/M/Y hh:mm')`
console.log(dateString);
This snippet, in turn, will produce the output of "1/1/1970 11:40"
Upvotes: 1
Reputation: 874
One simple approach can be like this:
workFrom = "11:40";
time = new Date("01/01/1970" + " " + workFrom);
console.log(time.getDate() +'/'+ time.getMonth() +'/'+ ime.getFullYear()+ ' '+ time.getHours() + ':' + time.getMinutes());
Upvotes: 1
Reputation: 2810
var d = new Date("01/01/1970 11:40:0:0");
you can do it:
date="01/01/1970";
workFrom="11:40";
d = new Date(date +" "+workFrom);
Upvotes: 0