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>
In the moment. js package, the miliseconds() method returns the number of milliseconds present in a date or time. It can also be used to set the milliseconds of a date or time. Note: The milliseconds() method is the same as millisecond() method.
add(Object); moment(). add(Duration); Using the add method we can add number, hours, days etc.
To add time, pass the key of what time you want to add, and the amount you want to add. moment(). add(7, 'days');
The add() method in moment. js adds time to a particular time. We can add more days, more hours, more weeks, more months, and so on.
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 tomoment.defaultFormat
. Out of the box,moment.defaultFormat
is the ISO8601 formatYYYY-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>
There is certainly a millisecond
method which adds milliseconds. See the docs.
You can also see that there is a formatting shortcode for milliseconds - ms
in the table here.
String formatting may be of use
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With