[英]How can I subtract 1 month using moment.js?
I want to subtract 1 month from a given date in (DD/MM/YYYY) format, but when I do that using moment.js, it gives me the result as 01/12/2020.我想从(DD/MM/YYYY)格式的给定日期中减去 1 个月,但是当我使用 moment.js 执行此操作时,结果为 2020 年 1 月 12 日。 How can I resolve this?
我该如何解决这个问题? Basically when I click on the left-arrow, the month should be subtracted by 1 every
基本上当我点击左箭头时,每个月应该减去 1
var startOfMonth = moment().clone().startOf('month').format('DD/MM/YYYY');
leftArrow.on('click', function(){
var start = moment(startOfMonth).subtract(1, 'months').format("DD/MM/YYYY");
});
How can I subtract one month using moment.js?
如何使用 moment.js 减去一个月?
tl,dr; tl,博士;
moment(date).add(-1, 'months');
// or: moment(date).subtract(1, 'months');
initial answer:初步答案:
Here's a basic example.这是一个基本的例子。
It stores the date as a moment object, which you then modify by adding or subtracting a month without ever caring what its current value is.它将日期存储为一个时刻 object,然后您可以通过添加或减去一个月来修改它,而不用关心它的当前值是多少。 You could also store it as a JavaScript Date object, which is useful when you have to communicate it to an external entity (a db, the browser, etc...).
您还可以将其存储为 JavaScript 日期 object,这在您必须将其与外部实体(数据库、浏览器等)通信时很有用。
Take away points:带走点:
setDate
function)setDate
函数中) // set initial date let storedDate = moment.now(); // update DOM setDate(storedDate); function setDate(date) { document.getElementById('text').innerText = moment(date).format('MMMM YYYY'); } function addMonths(months) { // change stored date storedDate = moment(storedDate).add(months, 'months'); // update DOM setDate(storedDate); }
#text { min-width: 120px; text-align: center; display: inline-block } button { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script> <div> <button onclick="addMonths(-1)"><</button> <span id="text"></span> <button onclick="addMonths(1)">></button> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.