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

javascript - How to append milliseconds to the given date in moment js? - Stack Overflow

programmeradmin0浏览0评论

Is there any way to format the below date which has HH:MM:SS as time format into HH:MM:SS:MMM in moment js?

2016-01-10T00:00:00+05:30

Can it be converted into the format like the below one?

2016-01-10T00:00:00.000+05:30

Simple JS Code:

var pop = moment('2016-01-03');
var pop1 = pop.add(1,'week');
console.log(pop1.format());
<script src=".js"></script>

Is there any way to format the below date which has HH:MM:SS as time format into HH:MM:SS:MMM in moment js?

2016-01-10T00:00:00+05:30

Can it be converted into the format like the below one?

2016-01-10T00:00:00.000+05:30

Simple JS Code:

var pop = moment('2016-01-03');
var pop1 = pop.add(1,'week');
console.log(pop1.format());
<script src="http://momentjs.com/downloads/moment.js"></script>

Share Improve this question edited Nov 13, 2019 at 5:07 Catfish 19.3k60 gold badges213 silver badges358 bronze badges asked Oct 13, 2016 at 10:28 Batman25663Batman25663 2721 gold badge3 silver badges12 bronze badges 1
  • 1 Have you looked through their API docs? – evolutionxbox Commented Oct 13, 2016 at 10:31
Add a comment  | 

1 Answer 1

Reset to default 15

You can pass a custom string format argument to the format method in order to customize format output. In your case you can do:

pop1.format('YYYY-MM-DDTHH:mm:ss.SSSZ');

where mm means minutes (00..59), ss seconds (00..59) and SSS fractional seconds (000..999).

The docs says that if you do not pass any arguments to format:

As of version 1.5.0, calling moment#format without a format will default to moment.defaultFormat. Out of the box, moment.defaultFormat is the ISO8601 format YYYY-MM-DDTHH:mm:ssZ.

So if you want to change the way format() (without parameters) works, you can change moment.defaultFormat, for example:

moment.defaultFormat = 'YYYY-MM-DDTHH:mm:ss.SSSZ';

Here there is a live example:

var pop = moment('2016-01-03');
var pop1 = pop.add(1,'week');

// By default format() wil give you results in YYYY-MM-DDTHH:mm:ssZ
console.log(pop1.format()); // 2016-01-10T00:00:00+05:30
// You can pass a custom format string to the format method
console.log(pop1.format('YYYY-MM-DDTHH:mm:ss.SSSZ')); // 2016-01-10T00:00:00.000+05:30

// You can change defaultFormat according your needs
moment.defaultFormat = 'YYYY-MM-DDTHH:mm:ss.SSSZ';
console.log(pop1.format()); // 2016-01-10T00:00:00.000+05:30
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论