Batman25663
Batman25663

Reputation: 272

How to append milliseconds to the given date in moment js?

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>

Upvotes: 6

Views: 21039

Answers (1)

VincenzoC
VincenzoC

Reputation: 31482

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>

Upvotes: 15

Related Questions