简体   繁体   English

更新moment.js的持续时间

[英]Update a moment.js duration

Is it possible to update a moment.js duration using the standard methods without using the add/subtract methods? 是否可以使用标准方法而不使用加/减方法来更新moment.js持续时间?

For example, create the moment: 例如,创建时刻:

d = moment.duration({
    seconds: 34,
    minutes: 55,
    hours: 2,
});

Then update only the minutes but keep the seconds and hours the same? 然后仅更新分钟,但保持秒和小时不变吗?

I can do something like this: 我可以这样做:

newD = moment.duration({
    seconds: value.seconds(),
    minutes: 32,
    hours: value.hours(),
});

Or work out whether I need to add/subtract from the original and then use: 或确定我是否需要添加/减去原始内容,然后使用:

d.subtract(23).minutes();

But I feel like I'm missing something obvious here. 但是我感觉这里缺少明显的东西。

Rather than add/subtract from the moment, I'd like to replace one of the values stores in the object as seen in _data: 我不想立即添加/减去,而是要替换对象中存储的值之一,如_data所示:

 _data: [object Object] {
     days: 0,
     hours: 1,
     milliseconds: 0,
     minutes: 20,
     months: 0,
     seconds: 0,
     years: 0
 },

Ie the equivalent of: 即相当于:

d._data.minutes = 3;

But it needs to also update the other properties of the object. 但是它还需要更新对象的其他属性。

Looking at momentjs API (and code), there seems to be no setter methods on duration object for time units (hours, minutes, seconds etc). 看一下momentjs API(和代码),在持续时间对象上似乎没有针对时间单位(小时,分钟,秒等)的setter方法。 All momentjs provides for these time units is getters. 这些时间单位所提供的momentjs都是吸气剂。 So a good way to do this is the way you did it in the question itself, creating a new duration object using the values from an existing one. 因此,执行此操作的一种好方法是您在问题本身中执行此操作的方式,即使用现有对象中的值创建一个新的工时对象。

var d = moment.duration({
    seconds: 34,
    minutes: 55,
    hours: 2
});

var newD = moment.duration({
    seconds: d.value(),
    minutes: 32,
    hours: d.value()
});

Updating the underlying _data property seems to update the specific time unit, but it doesn't update the duration object itself. 更新基础_data属性似乎会更新特定的时间单位,但不会更新duration对象本身。 So other methods like humanize do not provide us with the updated value. 因此,其他类似人性化的方法无法为我们提供最新的价值。

var d = moment.duration({
    seconds: 34,
    minutes: 55,
    hours: 2
});

d.humanize() // '3 hours'
d._data.hours = 5;
d.hours() // 5 -> This is being updated
d.humanize() // '3 hours' -> This one isn't

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM