red*_*rom 46 javascript date momentjs
我试图使用以下方法获取上个月的最后一天:
var dateFrom = moment(dateFrom).subtract(1, 'months').format('YYYY-MM-DD');
Run Code Online (Sandbox Code Playgroud)
哪里:
dateFrom = 2014-11-30
Run Code Online (Sandbox Code Playgroud)
但使用后
subtract(1, 'months')
Run Code Online (Sandbox Code Playgroud)
它返回日期
DATE_FROM: "2014-10-30"
Run Code Online (Sandbox Code Playgroud)
但是10月的最后一天是31.
我该怎么解决?
非常感谢任何帮助.
Mor*_*osh 104
只需添加一个endOf('month')电话:
var dateFrom = moment(dateFrom).subtract(1,'months').endOf('month').format('YYYY-MM-DD');
http://jsfiddle.net/r42jg/327/
以当前日期为基础的上个月的第一个日期和上个月的最后一个日期。日期的格式根据情况而变化。(日-月-年)
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);
Run Code Online (Sandbox Code Playgroud)
一个更简单的解决方案是使用moment.date(0). 该.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"));Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46554 次 |
| 最近记录: |