I have a date value like this "2015-09-30T17:32:29.000-05:00" and when i get the getMilliseconds from this date as below , i am just getting 0 and not getting 000. Why? I want to get three digit as milli seconds?
myDate =2015-09-30T17:33:28.000-04:00;
var msecs = myDate.getMilliseconds()
i am getting msecs =0. I would like to get msecs as 000. How do i acheive this?
I have a date value like this "2015-09-30T17:32:29.000-05:00" and when i get the getMilliseconds from this date as below , i am just getting 0 and not getting 000. Why? I want to get three digit as milli seconds?
myDate =2015-09-30T17:33:28.000-04:00;
var msecs = myDate.getMilliseconds()
i am getting msecs =0. I would like to get msecs as 000. How do i acheive this?
Share Improve this question edited Sep 30, 2015 at 20:36 user5394858 asked Sep 30, 2015 at 20:25 user5394858user5394858 514 bronze badges 11- 3 duplicate, or well, answered by stackoverflow./questions/2998784/… what you want is basically padding the string representation of a number with "0" strings. – thomas Commented Sep 30, 2015 at 20:29
- 2 also here: stackoverflow./questions/10841773/… – GrafiCode Commented Sep 30, 2015 at 20:29
- 2 how do you get that when you are using a Date method on a string? – charlietfl Commented Sep 30, 2015 at 20:30
-
3
@dandavis - e on!
if (msecs == 0) return "000";
– Igor Commented Sep 30, 2015 at 20:44 - 2 @dandavis - I am joking. The OP was only concerned with 0 in his question. – Igor Commented Sep 30, 2015 at 20:45
1 Answer
Reset to default 10You can pad the number of milliseconds with two zeros (to ensure that there are at least three digits) and then use String.prototype.slice()
to get only the last 3 characters (digits).
var msecs = ('00' + myDate.getMilliseconds()).slice(-3);
That way, even if the number of milliseconds returned is already three digits long, the zeros added as padding will be stripped when you slice()
the string passing -3
as the argument:
// when the number of milliseconds is 123:
myDate.getMilliseconds() === 123
'00' + myDate.getMilliseconds() === '00123'
('00' + myDate.getMilliseconds()).slice(-3) === '123'
// or, when the number is 0:
myDate.getMilliseconds() === 0
'00' + myDate.getMilliseconds() === '000'
('00' + myDate.getMilliseconds()).slice(-3) === '000'