Javascript 使用时刻获取上个月的月份名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42245587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:00:37  来源:igfitidea点击:

Get month name of last month using moment

javascriptmomentjs

提问by wawanopoulos

I use the following code to get startDate and endDate of the last months.

我使用以下代码获取最近几个月的 startDate 和 endDate。

// Previous month
var startDateMonthMinusOne = moment().subtract(1, "month").startOf("month").unix();
var endDateMonthMinusOne   = moment().subtract(1, "month").endOf("month").unix();

// Previous month - 1

var startDateMonthMinusOne = moment().subtract(2, "month").startOf("month").unix();
var endDateMonthMinusOne   = moment().subtract(2, "month").endOf("month").unix();

How can i do to get also the month name ? (January, February, ...)

我怎样才能获得月份名称?(一月二月, ...)

回答by NineBerry

Instead of unix()use the format()function to format the datetime using the MMMMformat specifier for the month name.

而不是unix()使用该format()函数使用MMMM月份名称的格式说明符来格式化日期时间。

var monthMinusOneName =  moment().subtract(1, "month").startOf("month").format('MMMM');

See the chapter Display / Format in the documentation

请参阅文档中的“显示/格式”一章

回答by VincenzoC

You can simply use format('MMMM').

您可以简单地使用format('MMMM').

Here a working example:

这是一个工作示例:

var currMonthName  = moment().format('MMMM');
var prevMonthName  = moment().subtract(1, "month").format('MMMM');

console.log(currMonthName);
console.log(prevMonthName);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>