Swathi
Swathi

Reputation: 119

Is there any way to get the unit and value of the given duration using moment.js

I have duration value as below:

var duration = "7 days";

From the above I want to get the object which has value and unit,like:

time {
  value: 7,
  unit: days
}

I know that I can get the value and unit using JavaScript. But I'm thinking it would be better if i can do this using some method of momentjs. I went through momentjs documentation, but I didn't find one.

Is there any way to achieve this using momentjs?

Upvotes: 2

Views: 1666

Answers (3)

Célia
Célia

Reputation: 359

I was in a similar situation today and I found a simple solution.

In my case, I had to say to the user that he could select a range of 1 month (max). But whether the user selects 30 days or 34 days, humanize() returns "1 month" in both cases. That's how I ended up here. Hope this will help some people to save some time.

Solution

So instead of using moment.duration().humanize(), using moment.duration().days() or .asDays() did the trick.

You can also use .get(unit) to get the remainder.
Example : if you have a duration of 31 days, then do duration.get('days'), it returns 1.

Same goes for every unit. See : https://momentjs.com/docs/#/durations

toJSON() ?

Nice try, but moment.duration().toJSON() as proposed in another answer won't be of any help in this situation because it returns an object with a string in the form of "PT5M", not really what we wanted.

See: http://momentjs.com/docs/#/durations/as-json/

Upvotes: 0

Victor.dMdB
Victor.dMdB

Reputation: 1019

I wrote this function (in .ts) to get the timescale :

export enum Unit {
    minute,
    hour,
    day,
    week,
    month
};

export type Duration = {
    value   : number;
    unit    : keyof typeof Unit;
}

const getTimescale = ( input : string ) => { 
    const duration = moment.duration(input);
    const units = Object.keys(Unit).filter(k => typeof Unit[k as any] === "number").reverse() as Array<keyof typeof Unit>;

    let result = {} as Duration;
    for (let i = 0; i < units.length; i++) {
        let value = duration.get(units[i] as keyof typeof Unit);
        if( result.unit && value ){
            if( moment.duration(duration, units[i] as keyof typeof Unit).subtract( moment.duration( result.value, result.unit )) > moment.duration(0) ){
                return { value, unit : units[i] as keyof typeof Unit }
            } else {
                return result;
            }
        };
        result = { value, unit : units[i] as keyof typeof Unit };
    };

    return result;
} 

Upvotes: 0

MrE
MrE

Reputation: 20788

from the docs you can get: http://momentjs.com/docs/#/durations/as-json/

moment.duration().toJSON();

When serializing a duration object to JSON, it will be be represented as an ISO8601 string.

JSON.stringify({
    postDuration : moment.duration(5, 'm')
}); // '{"postDuration":"PT5M"}'

Upvotes: 1

Related Questions