At the moment I have an input field that allows you to choose an hour by entering two digits. for example you could choose 12 for 12 hours.
Is there a way using moment to convert that number into milliseconds using MomentJS?
At the moment I am having to do the below maths. I can't see in the Moment docs that this is doable.
var timeHH = scope.session.timeHH * 3600;
This works out the seconds, then later I mulitply it by 1000 for the milliseconds value.Answer1:
Is there a way using moment to convert that number into <s>mini</s> milliseconds using moment?</blockquote>
There may be, but there's absolutely no reason to use MomentJS for this, and doing so would be roundabout and inefficient. It's quite straightforward:
hours * 3600000 is milliseconds. There are no weird special cases to handle, etc., unless you're handling converting a particular period of hours of a real time (say, the 10 hours from 8 p.m. December 31st 2005 GMT) and want to handle leap second insertions (there was one that night at midnight), but MomentJS doesn't do that anyway.
For this particular use case, the right thing to do is a manual calculation. For the sake of completeness and in the event you needed to do more complicated calculations, to do this with Moment, you would use the duration type. The duration type will allow you to convert from one unit value to another, and if you had to make several unit conversions instead of just this one it would be a good choice.
moment.duration(12, 'hours').asMilliseconds() 43200000
In addition to converting to milliseconds, you could convert to any other unit:
var dur = moment.duration(12, 'hours'); dur.asMilliseconds(); 43200000 dur.asDays(); 0.5 dur.asYears(); 0.001368953503494254
In addition to the as functions, you can get the parts of the duration broken out:
var dur = moment.duration(12.5, 'hours'); dur.hours(); 12 dur.minutes(); 30 dur.seconds(); 0
Or call humanize to get a human readable string that is an estimate of the duration's length:
var dur = moment.duration(42, 'hours'); dur.humanize(); "2 days"
You can also do math with durations. See the docs for more info: <a href="http://momentjs.com/docs/#/durations/" rel="nofollow">http://momentjs.com/docs/#/durations/</a>Answer3:
You can try the following hack(assuming hours in 24-Hours format) :
var momObj = moment('12', 'HH'); var x = momObj.diff(moment().startOf('day')); console.log(x) //43200000