MomentJS - Creating


Advertisements

This method is used to create the duration.

Syntax

moment.duration(Number, String);
moment.duration(Number);
moment.duration(Object);
moment.duration(String);

Example

var k = moment.duration(500);
JSON.stringify(k._data) // to get the object details from duration

The duration method gives the object with all details. The structure of duration that is visible in a console is shown here −

Duration

Output

Duration Method

Example

var k = moment.duration(1500);

Output

Moment Duration

It also possible to create duration with units as params. Observe the following example for a better understanding −

Example

var k = moment.duration(5, 'seconds');

Output

Create Duration

Example

var k = moment.duration(12, 'months');

Output

Note that we have used 12 months in the duration, so it directly shows it in years as shown below −

Duration Years

Example

var k = moment.duration(2, 'weeks');

The week’s details are shown in for days. 2 weeks counts to 14 days as shown below −

Output

Duration Weeks

The units which can be used with duration are years, months, weeks, days, hours, minutes, seconds and milliseconds. You can use the key/shorthand version discussed in earlier chapters for units with duration.

You can also update days, hour, minute, seconds as shown below −

Example

var k = moment.duration('6.23:50:40');

Output

Duration Update Days

Example with parsing method

var k = moment.duration('P5Y8M9DT4H5M25S');

Output

Parsing Method
momentjs_durations.htm
Advertisements