Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtract time from date - moment js

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

like image 657
Frank Avatar asked Jun 26 '14 10:06

Frank


People also ask

How do you subtract time in a moment?

MomentJS - Subtract Methodsubtract(2, 'months'); // subtract object method var changeddate1 = moment(). subtract({ days: 5, months: 2 }); //using duration in subract method var duration = moment. duration({ 'days': 10 }); var changeddate2 = moment([2017, 10, 15]). subtract(duration);


2 Answers

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" 
like image 199
joews Avatar answered Oct 03 '22 07:10

joews


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>
like image 34
Michael Richardson Avatar answered Oct 03 '22 09:10

Michael Richardson