MomentJS - Subtract



Just like the add method, subtract allows to subtract days, months, hours, minutes, seconds etc., from a given date.

Syntax

moment().subtract(Number, String);
moment().subtract(Duration);
moment().subtract(Object);

Observe the following example that shows how to use the subtract method −

Example

<html>
   <head>
      <title>MomentJS - Subtract Method</title>
      <script type="text/JavaScript"    src="https://MomentJS.com/downloads/moment.js"></script>
      <style>
         div {
            border: solid 1px #ccc;
            padding:10px;
            font-family: "Segoe UI",Arial,sans-serif;
            width: 75%;
         }
      </style>
   </head>
   <body>
      <h1>MomentJS - Subtract Method</h1>
      <div style="font-size:25px" id="currentdate"></div>
      <br/>
      <br/>
      <div style="font-size:25px" id="changeddate"></div>
      <br/>
      <br/>
      <div style="font-size:25px" id="changeddate1"></div>
      <br/>
      <br/>
      <div style="font-size:25px" id="changeddate2"v</div>
      <script type="text/JavaScript">
         var day = moment();
         document.getElementById("currentdate").innerHTML = "Current Date: " + day._d;
         var changeddate = moment().subtract(5, 'days').subtract(2, 'months');
         document.getElementById("changeddate").innerHTML = "Subtracting 5 days and 2 month using chaining method: " + changeddate._d;
         var changeddate1 = moment().subtract({ days: 5, months: 2 });
         document.getElementById("changeddate1").innerHTML = "Subtracting 5 days and 2 month using object method: " + changeddate1._d;
         var duration = moment.duration({ 'days': 10 });
         var changeddate2 = moment([2017, 10, 15]).subtract(duration);
         document.getElementById("changeddate2").innerHTML = "Subtracting 10 days from given date using duration method: " + changeddate2._d;
      </script>
   </body>
</html>

Output

To subtract days, months from the date we have done following −

//chaining subtract method
var changeddate = moment().subtract(5, 'days').subtract(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);

The output for the same in shown in the above example.

momentjs_manipulate_date_and_time.htm
Advertisements