2

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

3
  • You can use moment package to parse and validate dates. Commented Nov 8, 2016 at 6:51
  • I am a newbie to Node JS, So could you be more elaborate on how to convert @abhishekkannojia Commented Nov 8, 2016 at 7:16
  • 1
    You don't need a library: '11:40'.split(':').reduce((h,m)=> new Date(h*3.6e6 + m*6e4).toISOString()). Commented Nov 8, 2016 at 7:20

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think you need parts[0]*60 + +parts[1] but otherwise, great.
First operand parts[0]*60 is number, then second operand parts[1] will be converted to number
No, it won't. While parts[1]*60 returns a number, parts[0] is a string, so it will be concatenated, not added. And you have the indices reversed, you want parts[0]*60, etc. Those two errors mean the value of minutes is "240011" instead of 700 and the result is "1970-06-16T16:11:00.000Z" instead of "1970-01-01T11:40:00Z". ;-)
1

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

Comments

1

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"

Comments

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

1 Comment

Parsing strings with the Date constructor (or Date.parse, they are equivalent for parsing) is strongly discouraged.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.