如何将分钟添加到时间字符串

How to add minutes to a time string?

本文关键字:时间 字符串 添加 分钟      更新时间:2023-09-26

我正在使用momentjs来操纵时间。我有一个小时,一分钟,第二个字符串,比如'00:30:00'。我想再花几分钟。使用momentjs,我可以将这个字符串转换成分钟,然后我可以很容易地添加我想要的分钟。但我怎么才能回到蜇人的地方呢?

ex - moment.duration('00:30:00').asMinutes;给我几分钟。假设这是30分钟,我可以再加30分钟使它变成60分钟。我如何转换60分钟到这个字符串再次使用momentjs?

打印

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

I am getting

[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

您需要使用.add

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

然后你可以在上面运行.asMinutes来打印总持续时间

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

只有当您想要拉总分钟数时,您才希望始终使用.asMinutes

您可以通过克隆时刻来解决这个问题,如下所述。

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