【问题标题】:subtract time from date - moment js从日期中减去时间 - 时刻 js
【发布时间】:2014-06-26 10:57:08
【问题描述】:

例如,我有这个日期时间:

01:20:00 06-26-2014

我想减去这样的时间:

00:03:15

之后我想像这样格式化结果:

3 hours and 15 minutes earlier.

如何使用moment.js 做到这一点?

编辑:我试过了:

var time = moment( "00:03:15" );
var date = moment( "2014-06-07 09:22:06" );

date.subtract (time); 

但是结果和date一样

谢谢

【问题讨论】:

    标签: javascript momentjs


    【解决方案1】:

    Moment.subtract 不支持 Moment 类型的参数 - documentation

    moment().subtract(String, Number);
    moment().subtract(Number, String); // 2.0.0
    moment().subtract(String, String); // 2.7.0
    moment().subtract(Duration); // 1.6.0
    moment().subtract(Object);
    

    最简单的解决方案是将时间增量指定为对象:

    // Assumes string is hh:mm:ss
    var myString = "03:15:00",
        myStringParts = myString.split(':'),
        hourDelta: +myStringParts[0],
        minuteDelta: +myStringParts[1];
    
    
    date.subtract({ hours: hourDelta, minutes: minuteDelta});
    date.toString()
    // -> "Sat Jun 07 2014 06:07:06 GMT+0100"
    

    【讨论】:

    • 好的,谢谢,但是如果我只能像 00:03:15 这样的字符串那样有时间
    • 从该格式中提取值并不难。我会更新我的答案。
    【解决方案2】:

    有一个简单的函数subtract,矩库让我们可以从某个时间中减去时间。 使用起来也很简单。

    moment(Date.now()).subtract(7, 'days'); // This will subtract 7 days from current time
    moment(Date.now()).subtract(3, 'd'); // This will subtract 3 days from current time
    
    //You can do this for days, years, months, hours, minutes, seconds
    //You can also subtract multiple things simulatneously
    
    //You can chain it like this.
    moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); // This will subtract 3 days and 5 hours from current time
    
    //You can also use it as object literal
    moment(Date.now()).subtract({days:3, hours:5}); // This will subtract 3 days and 5 hours from current time
    

    希望这会有所帮助!

    【讨论】:

    • 我认为有一个错字。在moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); 应该是逗号而不是句点不应该是moment(Date.now()).subtract(3, 'd').subtract(5, 'h');
    【解决方案3】:

    您可以使用 Moment.js Durations 创建一个更简洁的实现。无需手动解析。

    var time = moment.duration("00:03:15");
    var date = moment("2014-06-07 09:22:06");
    date.subtract(time);
    $('#MomentRocks').text(date.format())
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>
    <span id="MomentRocks"></span>

    【讨论】:

      【解决方案4】:

      我可能在这里遗漏了您的问题中的某些内容...但据我所知,通过使用 subtract 方法,这应该是您想要做的:

      var timeStr = "00:03:15";
          timeStr = timeStr.split(':');
      
      var h = timeStr[1],
          m = timeStr[2];
      
      var newTime = moment("01:20:00 06-26-2014")
          .subtract({'hours': h, 'minutes': m})
          .format('hh:mm');
      
      var str = h + " hours and " + m + " minutes earlier: " + newTime;
      
      console.log(str); // 3 hours and 15 minutes earlier: 10:05
      

      $(document).ready(function(){    
           var timeStr = "00:03:15";
              timeStr = timeStr.split(':');
      
          var h = timeStr[1],
              m = timeStr[2];
      
          var newTime = moment("01:20:00 06-26-2014")
              .subtract({'hours': h, 'minutes': m})
              .format('hh:mm');
      
          var str = h + " hours and " + m + " minutes earlier: " + newTime;
      
          $('#new-time').html(str);
      })
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
      
      
      <p id="new-time"></p>

      【讨论】:

      • 好的,谢谢,但如果我只能像 00:03:15 这样的字符串有时间。
      • 您需要添加解析该字符串的额外步骤。作为旁注,该字符串是 3 分 15 秒(不是小时和分钟)。答案已更新。
      【解决方案5】:

      Michael Richardson 的解决方案很棒。如果你想减去日期(因为如果你搜索它,Google 会指向你这里),你也可以说:

      var date1 = moment( "2014-06-07 00:03:00" );
      var date2 = moment( "2014-06-07 09:22:00" );
      
      differenceInMs = date2.diff(date1); // diff yields milliseconds
      duration = moment.duration(differenceInMs); // moment.duration accepts ms
      differenceInMinutes = duration.asMinutes(); // if you would like to have the output 559
      

      【讨论】:

        【解决方案6】:

        我使用 moment.js http://momentjs.com/

        var start = moment(StartTimeString).toDate().getTime();
        var end = moment(EndTimeString).toDate().getTime();
        var timespan = end - start;
        var duration = moment(timespan);
        var output = duration.format("YYYY-MM-DDTHH:mm:ss");
        

        【讨论】:

          【解决方案7】:

          如果只想使用 moment js 进行时间减法,请参见示例...干杯?

             // subtractTimes(["05:00", "00:30", "00:20"]) --- 04:10
          
          
             subtractTimes(times) {
              let totalDiff = 0
              for (let i = 0; i < times.length; i++) {
                let duration = moment.duration(times[i]).as('milliseconds')
                if (i == 0) {
                  totalDiff = duration
                }
                if (i > 0) {
                  totalDiff = totalDiff - duration
                }
              }
              return moment.utc(totalDiff).format("HH:mm")
            }
          

          【讨论】:

            猜你喜欢
            • 2020-01-14
            • 2020-02-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-02-14
            • 2020-01-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多