Javascript 在 moment.js 中获取所有月份的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29303164/
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 03:08:27  来源:igfitidea点击:

Get all months name from year in moment.js

javascriptmomentjs

提问by Ramesh Rajendran

I want to get all months name from year in moment.js

我想在 moment.js 中获取所有月份的名称

if the year is 2011, then i want to all months name in momentjs

如果年份是2011,那么我想在momentjs中命名所有月份

i have tried this below code, but it's not working for me.

我在下面的代码中尝试过这个,但它对我不起作用。

var xxx = moment().months(2011);

Showing result is

显示结果是

enter image description here

在此处输入图片说明

also i have tried xxx.months(), but it's return result is 7

我也试过xxx.months(),但它的返回结果是7

but i want jan,feb,mar,......dec. hmm What can i do?

但我想要jan,feb,mar,......dec嗯我能做什么?

回答by Klaster_1

There happens to be a function for that:

恰好有一个函数:

moment.monthsShort()
// ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]

Or the same using manual formatting:

或者同样使用手动格式化:

Array.apply(0, Array(12)).map(function(_,i){return moment().month(i).format('MMM')})

I guess you want to display all names utilizing Moment.js locale data, which is a reasonable approach.

我猜您想使用 Moment.js 区域设置数据显示所有名称,这是一种合理的方法。

回答by Mikel Sanchez

Using moment.js you have the following methods:

使用 moment.js 您有以下方法:

moment.months() // long names

returns:

返回:

[ 'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December' ]

and

moment.monthsShort() // short names

returns:

返回:

["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

回答by bvaughn

if the year is 2011, then i want to all months name in momentjs

如果年份是 2011,那么我想在 momentjs 中命名所有月份

Why does the year matter? Month names don't change.

为什么年份很重要?月份名称不变。

You could get month names from Moment like so:

您可以像这样从 Moment 获取月份名称:

var m = moment();
for (var i = 0; i < 12; i++) {
 console.log(m.months(i).format('MMMM'));
}

回答by Mr. Polywhirl

/**
 * Returns an array of all month names for a given language
 * in the specified format.
 *
 * @param lang {string} Language code
 * @param frmt {string} Possible values: {'M','MM','MMM','MMMM'}
 * @return the array of month names
 */
function getMonthNames(lang, frmt) {
  var userLang = moment.lang();            // Save user language
  moment.lang(lang);                       // Switch to specified language
  var months = [];                         // Months array
  var m = moment("2011");                  // Create a moment in 2011
  for (var i = 0; i < 12; i++)             // Loop from 0 to 12 (exclusive)
    months.push(m.months(i).format(frmt)); // Append the formatted month
  moment.lang(userLang);                   // Restore user language
  return months;                           // Return the array of months
}

function println(text) {
  text = arguments.length > 1 ? [].join.call(arguments, ' ') : text;
  document.getElementById('disp').innerHTML += text + '\n';
}

println('English:', getMonthNames('en-US', 'MMM'));
println('Bengali:', getMonthNames('bn', 'MMM'));
println('Espa?ol:', getMonthNames('es', 'MMM'));
#disp {
  white-space: pre;
  font-family: monospace;
}
<!-- http://cdnjs.com/libraries/moment.js/ -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js"></script>

<div id="disp"></div>

Output

输出

English: Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
Bengali: ????,???,?????,???,??,???,???,??,?????,?????,??,??????
Espa?ol: ene.,feb.,mar.,abr.,may.,jun.,jul.,ago.,sep.,oct.,nov.,dic.

回答by Neha

You can use following function to get a list of Weekdays and Months for listing purpose -

您可以使用以下函数来获取工作日和月份的列表以供上市 -

var iIndex, 
sArrMonths, sMonth;
for(iIndex = 0; iIndex < 12; iIndex++)
{
    sMonth = moment.localeData().months(moment([0,iIndex]), "");
    sArrMonths.push(sMonth);
}

You can check live example here - Localized Month and Weekdays List

您可以在此处查看实时示例 -本地化的月份和工作日列表

回答by KJ Price

You are going to have to access the months from an array:

您将不得不从数组中访问月份:

var months = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];

var monthInt = new Date().getMonth();
var monthString = months[monthInt];

回答by Христи?ан С.

I needed an array with months number and months name to display them in ng-optiosn, so I extended a little bit Klaster_1's solution.

我需要一个带有月数和月名的数组来在 ng-optiosn 中显示它们,所以我扩展了一点 Klaster_1 的解决方案。

Array.apply(0, Array(12)).map(
                    function(_,i){
                          var elem    ={};
                          elem.id     = parseInt(i+1);
                          elem.name   = moment().month(i).format('MMM'); 
                          return elem;
                    }
              )

回答by gakeko betsi

If you want to list month names in a select in React:

如果你想在 React 的选择中列出月份名称:

  <select
    value={value}
    onChange={handleChange}>

         {moment.months().map(item => (
            <option key={item}>{item}</option>
         ))}

  </select>

回答by RubbelDieKatz

It's 2019 and you shouldn't be using moment.js anymore, since the vanilla Date()class has everything we need. Except for this little bit of functionality.

现在是 2019 年,你不应该再使用 moment.js,因为 vanillaDate()类拥有我们需要的一切。除了这个小功能。

Here's what I use: There's the monthsNPM modulewhich has all months in different languages. It's about 991 bytes gzipped.

这是我使用的:monthsNPM 模块包含不同语言的所有月份。压缩后大约有 991 个字节。

Example with proper importsyntax:

具有正确import语法的示例:

import months from 'months'

console.log(months.de)

Result:

结果:

[
  "Januar",
  "Februar",
  "M?rz",
  "April",
  "Mai",
  "Juni",
  "Juli",
  "August",
  "September",
  "Oktober",
  "November",
  "Dezember"
]