subtract time from date - moment js
Asked Answered
D

8

48

I have for instance this datetime:

01:20:00 06-26-2014

and I want to subtract a time like this:

00:03:15

after that I'd like to format the result like this:

3 hours and 15 minutes earlier.

How can I do that using moment.js ?

edit: I tried:

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

date.subtract (time); 

but the result is the same as date

Thanks

Daric answered 26/6, 2014 at 10:57 Comment(0)
P
62

Moment.subtract does not support an argument of type 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);

The simplest solution is to specify the time delta as an 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"
Purington answered 26/6, 2014 at 11:13 Comment(3)
ok thanks, but what if I can only have the time as String like 00:03:15Daric
It's not difficult to extract the values from that format. I will update my answer.Purington
This is much simpler with Moment.js DurationsEisenberg
E
45

You can create a much cleaner implementation with Moment.js Durations. No manual parsing necessary.

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>
Eisenberg answered 15/12, 2014 at 20:28 Comment(0)
W
24

There is a simple function subtract which moment library gives us to subtract time from some time. Using it is also very simple.

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

Hope this helps!

Wholly answered 31/7, 2019 at 9:20 Comment(1)
I think there's a typo. It should be comma instead of period at moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); Shouldn't it be moment(Date.now()).subtract(3, 'd').subtract(5, 'h');Adames
M
9

I might be missing something in your question here... but from what I can gather, by using the subtract method this should be what you're looking to do:

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>
Morula answered 26/6, 2014 at 11:9 Comment(2)
ok thanks, but what if I can only have the time as String like 00:03:15.Daric
You would need to add in the extra step of parsing that string. As a side note, that string is 3 minutes and 15 seconds (not hours and minutes). Answer updated.Morula
C
8

Michael Richardson's solution is great. If you would like to subtract dates (because Google will point you here if you search for it), you could also say:

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
Cryptic answered 18/6, 2016 at 9:7 Comment(0)
S
3

I use 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");
Soursop answered 17/6, 2016 at 3:24 Comment(0)
W
0

See Example if only want time subtraction using moment js ... cheers 😀

   // 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")
  }
Windjammer answered 29/6, 2021 at 2:56 Comment(0)
L
-1

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>
Latex answered 28/2, 2023 at 10:9 Comment(1)
Putting ['00','03','15']` into moment will give you "0000-03-15T00-00-00", so you are not subtracting from the time you think you are subtracting from. In general, I am not sure how this addresses the question.Browse

© 2022 - 2024 — McMap. All rights reserved.