Vignesh
Vignesh

Reputation: 151

Convert from String to DateTime in Node Js

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

Answers (4)

galkin
galkin

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

C'estLaVie
C'estLaVie

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

Siraj Hussain
Siraj Hussain

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

Simran
Simran

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

Related Questions