日期扩展javascript获取月份名称

时间:2017-01-11 13:35:29

标签: javascript date extension-methods

我努力在日期对象上进行扩展以返回当前月份的名称。如果调用方法d.getMonthText(),它应该返回(January)。

我已经在网上搜索了扩展程序,但我似乎无法弄明白。

6 个答案:

答案 0 :(得分:8)

只需将date.getMonth()方法值映射到月值

Date.prototype.getMonthText = function() {
  var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  return months[this.getMonth()];
}

var now = new Date();
var month = now.getMonthText();
console.log(month);

答案 1 :(得分:3)

虽然不推荐,但您可以通过其prototype属性向几乎任何javascript内置对象添加方法。

Date.prototype.getMonthName = function() {
    let months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];

    return months[this.getMonth()];
};

然后使用它:

let date = new Date();
let month = date.getMonthName();

答案 2 :(得分:1)

只是要添加一个选项,您可以考虑 toLocaleString ,它应该支持ECMA 402国际化API。它不是无处不在,但值得考虑未来,因为它将使用ISO 639-1语言代码返回任何语言的月份名称:



Date.prototype.getMonthName = function(lang) {
  // Default language is English
  lang = lang || 'en-GB';
  return this.toLocaleString(lang, {month:'long'});
}

console.log(new Date().getMonthName())        // English (default)

console.log(new Date().getMonthName('ar-sy')) // Arabic

console.log(new Date().getMonthName('es-py')) // Spanish




答案 3 :(得分:0)

你有一个非常基本的方式..这个函数会返回你的名字

<script>
function getMonthText(){
var month;
 switch (new Date().getMonth()) {
   case 0:
     month= "Jan";
     break;
   case 1:
     month= "Feb";
     break;
   case 2:
     month= "March";
     break;
   case 3:
     month= "April";
     break;
   case 4:
     month= "May";
     break;
   case 5:
     month= "June";
     break;
   case  6:
     month= "July";
     break;
   case  7:
     month= "August";
     break;
   case  8:
     month= "Sep";
     break;
   case  9:
     month= "Oct";
     break;
   case  10:
     month= "Nov";
     break;
   case  11:
     month= "Dec";
     break;
}}
 </script>

答案 4 :(得分:0)

ECMAScript 6版本:

getPreviousMonth(monthBefore) {
    let monthList = [];
    let date = new Date();
    for (let i = 0; i < monthBefore; i++) {
        date.setMonth(date.getMonth() - 1);
        monthList.push(date.toLocaleString('en-us', {
            month: 'long',
        }));
    }
    return monthList;
}

答案 5 :(得分:-2)

你可以修补Date原型对象并实现扩展方法:

Date.prototype.getMonthName = function() {
  return "January,February,March,April,May,June,July,August,September,October,November,December".split(",")[this.getMonth()];
}

相关问题