【问题标题】:How to add minutes to a time string?如何在时间字符串中添加分钟?
【发布时间】:2016-08-26 21:37:28
【问题描述】:

我正在使用 momentjs 来操纵时间。我有一个小时、分钟、第二个字符串,例如“00:30:00”。我想增加几分钟。使用 momentjs,我可以将此字符串转换为分钟,然后我可以轻松地添加我想要的分钟。但是我该如何让它回到原来的位置呢?

ex - moment.duration('00:30:00').asMinutes;会给我几分钟。 假设这给了 30 ,我可以再增加 30 分钟使其达到 60 分钟。 如何使用 momentjs 再次将 60mins 转换为该字符串?

关于打印

console.log(moment.duration('00:30:00').add(30, 'minutes'));

我来了

[object Object] { _bubble: function Zc(){var    a,b,c,d,e,f=this._milliseconds,g=this._days,h=this._months,i=this._data;
// if we have a mix of positive and negative values, bubble down first
// check: https://github.com/moment/moment/issues/2166
// The following code bubbles up values, see the tests for
// examples of what that means.
// convert days to months
// 12 months -> 1 year
return f>=0&&g>=0&&h>=0||0>=f&&0>=g&&0>=h||(f+=864e5*Yc(_c(h)+g),g=0,h=0),i.milliseconds=f%1e3,a=s(f/1e3),i.seconds=a%60,b=s(a/60),i.minutes=b%60,c=s(b/60),i.hours=c%24,g+=s(c/24),e=s($c(g)),h+=e,g-=Yc(_c(e)),d=s(h/12),h%=12,i.days=g,i.months=h,i.years=d,this},
  .... continued

【问题讨论】:

    标签: javascript momentjs


    【解决方案1】:

    您需要使用.add

    moment.duration('00:30:00').add(30, 'minutes);
    

    然后您可以在其上运行.asMinutes 以打印总时长。

    moment.duration('00:30:00').add(30, 'minutes').asMinutes();
    

    您希望始终最后使用.asMinutes,仅当您想要拉取总分钟数时。

    【讨论】:

    • 它给了我别的东西。你可以试一次吗
    • @scripter 请使用您的尝试和整个错误消息编辑您的问题。
    • @bevacqua 我明白了。如果我想将它转换回 String 为 '00:30:00' 格式怎么办?
    • @scripter 你可以做moment(30, 'mm').format('HH:mm:ss')
    【解决方案2】:

    您可以通过克隆时刻 as described here 来解决此问题。

    var timestring1 = "2016-05-09T00:00:00Z";
    var timestring2 = "2016-05-09T02:00:00Z";
    var startdate = moment(timestring1);
    var expected_enddate = moment(timestring2);
    var returned_endate = moment(startdate).add(30, 'minutes');  // see the cloning?
    returned_endate.isSame(expected_enddate)  // true
    

    【讨论】:

    • 我想将分钟转换成这样的字符串'00:30:00'。
    猜你喜欢
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多