MomentJS - 減法



就像 add 方法一樣,subtract 允許從某個給定日期中減去天、月、小時、分、秒等等。

語法

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

觀察以下示例來說明如何使用 subtract 方法 −

示例

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

輸出

要從日期中減去天和月,我們這樣做了 −

//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);

以上示例中展示了相同內容的輸出。

momentjs_manipulate_date_and_time.htm
廣告
© . All rights reserved.