最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - how to convert 0 to 000 in getMilliSeconds Javascript method? - Stack Overflow

programmeradmin1浏览0评论

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
 |  Show 6 more ments

1 Answer 1

Reset to default 10

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'
发布评论

评论列表(0)

  1. 暂无评论