javascript 从日期中减去时间-时刻js

pftdvrlh  于 2023-05-21  发布在  Java
关注(0)|答案(8)|浏览(136)

例如,我有这样的日期时间:

01:20:00 06-26-2014

我想减去这样的时间

00:03:15

在那之后,我想像这样格式化结果:
3 hours and 15 minutes earlier .
如何使用moment.js实现这一点?

edit:我试过了:

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

date.subtract (time);

但结果与date相同
谢谢

k4emjkb1

k4emjkb11#

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"
uoifb46i

uoifb46i2#

您可以使用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>
zd287kbt

zd287kbt3#

有一个简单的函数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

希望这有帮助!

rqdpfwrv

rqdpfwrv4#

我可能错过了你的问题中的一些东西...但是从我所能收集到的信息来看,通过使用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>
yrwegjxp

yrwegjxp5#

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

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
0ve6wy6x

0ve6wy6x6#

我使用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");
xesrikrc

xesrikrc7#

如果只想使用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")
  }
tct7dpnv

tct7dpnv8#

var timeArr = "00:03:15".split(':');

var newTime = moment(timeArr)
  .subtract({
    'seconds': 1
  })
  .format('hh:mm:ss');

var str = timeArr.join(':') + ' Before & after ' + newTime;

console.log(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>

相关问题