簡體   English   中英

MomentJS - 如何從日期獲取上個月的最后一天?

[英]MomentJS - How to get last day of previous month from date?

我正在嘗試使用以下方法獲取上個月的最后一天:

 var dateFrom = moment(dateFrom).subtract(1, 'months').format('YYYY-MM-DD');

在哪里:

dateFrom = 2014-11-30 

但是使用后

subtract(1, 'months')

它返回日期

DATE_FROM: "2014-10-30"

但是第 10 個月的最后一天是 31。

我該如何解決?

非常感謝您的幫助。

只需在您的電話中添加一個endOf('month')

var dateFrom = moment(dateFrom).subtract(1,'months').endOf('month').format('YYYY-MM-DD');

http://jsfiddle.net/r42jg/327/

一個更簡單的解決方案是使用moment.date(0) .date()函數取.date()第 1 到 n 天,但是,傳遞零或負數將產生上個月的日期。

例如,如果當前日期是 2 月 3 日:

 var _date = moment(); // 2018-02-03 (current day) var _date2 = moment().date(0) // 2018-01-31 (start of current month minus 1 day) var _date3 = moment().date(4) // 2018-02-04 (4th day of current month) var _date4 = moment().date(-4) // 2018-01-27 (start of current month minus 5 days) console.log(_date.format("YYYY-MM-DD")); console.log(_date2.format("YYYY-MM-DD")); console.log(_date3.format("YYYY-MM-DD")); console.log(_date4.format("YYYY-MM-DD"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>

moment().subtract(1, '月').endOf('月').format('YYYY-MM-DD')

從當前日期開始的上個月的第一個日期和上個月的最后一個日期。 日期的格式因人而異。 (DD-MM-YYYY)

console.log("last month first date");
   const lastmonthlastdate=moment().subtract(1, 'months').startOf('month').format('DD-MM-YYYY')
console.log(lastmonthlastdate);

console.log("lastmonth last date");
   const lastmonthfirstdate=moment().subtract(1, 'months').endOf('month').format('DD-MM-YYYY')
console.log(lastmonthfirstdate);

您可以獲取該月的第一天,然后減去 1 天以獲得上個月的最后一天。

const monthyear = moment().format('YYYY-MM')
const firstDay = moment(monthyear + "-01").format("YYYY-MM-DD");
// Subtract 1 day to get the end of the previous month
const dateTo = moment(firstDay).subtract('1', 'days').format("YYYY-MM-DD");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM