Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert 0 to 000 in getMilliSeconds Javascript method?

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?

like image 324
user5394858 Avatar asked Feb 09 '23 22:02

user5394858


1 Answers

You 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'
like image 53
rhino Avatar answered Feb 11 '23 13:02

rhino