885

如何从 JavaScript 中的这个日期对象生成月份的名称(例如:Oct/October)?

var objDate = new Date("10/11/2009");
4

39 回答 39

1376

较短的版本:

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

const d = new Date();
document.write("The current month is " + monthNames[d.getMonth()]);

注意(2019-03-08)-我最初在 2009 年写的这个答案已经过时了。请参阅David Storey 的答案以获得更好的解决方案。

于 2009-10-29T12:45:41.380 回答
1210

现在可以使用 ECMAScript 国际化 API 执行此操作:

const date = new Date(2009, 10, 10);  // 2009-11-10
const month = date.toLocaleString('default', { month: 'long' });
console.log(month);

'long'使用月份的全名、'short'简称和'narrow'更小的版本,例如字母语言中的第一个字母。

您可以将语言环境从浏览器更改为'default'您喜欢的任何语言(例如'en-us'),它将使用该语言/国家/地区的正确名称。

使用toLocaleStringapi,您每次都必须传入语言环境和选项。如果您打算在多个不同日期使用相同的语言环境信息和格式选项,则可以使用Intl.DateTimeFormat

const formatter = new Intl.DateTimeFormat('fr', { month: 'short' });
const month1 = formatter.format(new Date());
const month2 = formatter.format(new Date(2003, 5, 12));
console.log(`${month1} and ${month2}`); // current month in French and "juin".

有关更多信息,请参阅我关于Internationalization API的博文。

于 2013-09-06T01:08:34.490 回答
169

这是另一个,支持本地化:)

Date.prototype.getMonthName = function(lang) {
    lang = lang && (lang in Date.locale) ? lang : 'en';
    return Date.locale[lang].month_names[this.getMonth()];
};

Date.prototype.getMonthNameShort = function(lang) {
    lang = lang && (lang in Date.locale) ? lang : 'en';
    return Date.locale[lang].month_names_short[this.getMonth()];
};

Date.locale = {
    en: {
       month_names: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
       month_names_short: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    }
};

然后,您可以轻松添加对其他语言的支持:

Date.locale.fr = {month_names: [...]};
于 2009-10-29T12:54:35.997 回答
71

我衷心推荐format来自moment.js库的函数,你可以像这样使用它:

moment().format("MMM");  // "Apr" - current date
moment(new Date(2012, 01, 04)).format("MMM");  // "Feb" - from a local date
moment.utc(new Date(2012, 00, 04).format("MMM"); // "Jan" - from a UTC date

如果您需要月份的全名,请使用“MMMM”而不是“MMM”

除了一长串其他功能外,它还对国际化有很强的支持

于 2013-04-18T17:28:24.183 回答
64

如果您不介意扩展 Date 原型(并且有一些很好的理由不想这样做),您实际上可以想出一个非常简单的方法:

Date.prototype.monthNames = [
    "January", "February", "March",
    "April", "May", "June",
    "July", "August", "September",
    "October", "November", "December"
];

Date.prototype.getMonthName = function() {
    return this.monthNames[this.getMonth()];
};
Date.prototype.getShortMonthName = function () {
    return this.getMonthName().substr(0, 3);
};

// usage:
var d = new Date();
alert(d.getMonthName());      // "October"
alert(d.getShortMonthName()); // "Oct"

然后,这些函数将应用于所有javascript Date 对象。

于 2009-10-29T12:52:53.550 回答
29

您可以简单地使用 Date.toLocaleDateString() 并将所需的日期解析为参数

const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

const options = {  year: 'numeric', month: 'short', day: 'numeric' };

console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012

console.log(event.toLocaleDateString('en-US', options));
// US format 


// In case you only want the month
console.log(event.toLocaleDateString(undefined, { month: 'short'}));
console.log(event.toLocaleDateString(undefined, { month: 'long'}));

您可以在 Firefox文档中找到更多信息

于 2020-05-20T12:50:56.453 回答
28

如果我们需要传递我们的输入,那么我们需要使用以下方式

输入: '2020-12-28'

代码:

new Date('2020-12-28').toLocaleString('en-us',{month:'short', year:'numeric'})

输出: “2020 年 12 月”

于 2021-05-26T06:01:05.337 回答
24
Date.prototype.getMonthName = function() {
    var monthNames = [ "January", "February", "March", "April", "May", "June", 
                       "July", "August", "September", "October", "November", "December" ];
    return monthNames[this.getMonth()];
}

它可以用作

var month_Name = new Date().getMonthName();
于 2012-06-12T12:05:01.770 回答
23

document.write(new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}))

于 2020-01-17T13:42:54.507 回答
22

如果你赶时间......那么你去!

const date = new Date(Date.now());
date.toLocaleString('en-US', {month: 'short'}); // {month:'long'}

预期输出:"Apr"

于 2021-04-25T07:36:34.920 回答
21

日期对象的一些常见的简单过程可以通过这个来完成。

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];

function dateFormat1(d) {
  var t = new Date(d);
  return t.getDate() + ' ' + monthNames[t.getMonth()] + ', ' + t.getFullYear();
}

function dateFormat2(d) {
  var t = new Date(d);
  return t.getDate() + ' ' + monthShortNames[t.getMonth()] + ', ' + t.getFullYear();
}

console.log(dateFormat1(new Date()))
console.log(dateFormat2(new Date()))

或者您可以制作日期原型,例如

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


Date.prototype.getFormatDate = function() {
  var monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];
  return this.getDate() + ' ' + monthNames[this.getMonth()] + ', ' + this.getFullYear();
}


console.log(new Date().getMonthName())
console.log(new Date().getFormatDate())

前任:

var dateFormat3 = new Date().getMonthName(); # March

var dateFormat4 = new Date().getFormatDate(); # 16 March, 2017

于 2015-11-15T05:21:46.680 回答
16

你可以使用datejs来做到这一点。检查FormatSpecifiers, MMMM 为您提供月份名称:

var objDate = new Date("10/11/2009");
document.write(objDate.toString("MMMM"));

datejs 将其本地化为 150 多个语言环境!看这里

于 2009-10-29T15:35:42.927 回答
16

尝试:

var objDate = new Date("10/11/2009");

var strDate =
    objDate.toLocaleString("en", { day: "numeric" }) + ' ' +
    objDate.toLocaleString("en", { month: "long"  }) + ' ' +
    objDate.toLocaleString("en", { year: "numeric"});
于 2016-11-18T13:03:09.880 回答
16

另一种格式化日期的方法

new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}) //output: "May 21, 2019"
于 2019-05-21T04:14:26.797 回答
12

这是一种不依赖硬编码数组并支持多个语言环境的方法。

如果你需要一个完整的数组:

var monthsLocalizedArray = function(locale) {
    var result = [];
    for(var i = 0; i < 12; i++) {
        result.push(new Date(2010,i).toLocaleString(locale,{month:"long"}));
    }
    return result;
};

用法:

console.log(monthsLocalizedArray('en')); // -> ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
console.log(monthsLocalizedArray('bg')); // -> ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"]

如果您只需要选定的月份(更快):

var monthLocalizedString = function(month, locale) {
    return new Date(2010,month).toLocaleString(locale,{month:"long"});
};

用法:

console.log(monthLocalizedString(1, 'en')); // -> February
console.log(monthLocalizedString(1, 'bg')); // -> февруари
console.log(monthLocalizedString(1, 'de')); // -> Februar

在 Chrome 和 IE 11 上经过测试并且工作正常。在 mozilla 上需要进行一些修改,因为它会返回整个日期。

于 2014-02-13T08:08:52.513 回答
12

除了声明包含所有月份名称的数组然后用索引指向之外,我们还可以将它写成更短的版本,如下所示:

var objDate = new Date().toLocaleString("en-us", { month: "long" }); // result: August
var objDate = new Date().toLocaleString("en-us", { month: "short" }); // result: Aug
于 2016-08-05T06:05:21.220 回答
8

不幸的是,提取月份名称的最佳方法是使用 UTCString 表示:

Date.prototype.monthName = function() {
    return this.toUTCString().split(' ')[2]
};

d = new Date();
//=> Thu Mar 06 2014 23:05:21 GMT+0000 (GMT)

d.monthName();
//=> 'Mar'
于 2014-03-06T23:06:03.603 回答
7

您可以使用几种可用的日期格式化程序之一。由于这属于 JavaScript 规范,因此它可以在浏览器和服务器端模式下使用。

objDate.toString().split(" ")[1]; // gives short name, unsure about locale 
objDate.toLocaleDateString.split(" ")[0]; // gives long name

例如

js> objDate = new Date(new Date() - 9876543210)
Mon Feb 04 2013 12:37:09 GMT-0800 (PST)
js> objDate.toString().split(" ")[1]
Feb
js> objDate.toLocaleString().split(" ")[0]
February

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date上还有更多内容

于 2013-05-30T04:14:23.787 回答
7

现在的自然格式是使用 Moment.js。

以字符串格式获取月份的方法在 Moment.js 中非常简单,无需在代码中硬编码月份名称:以月份名称格式和全年(2015 年 5 月)获取当前月份和年份:

  moment(new Date).format("MMMM YYYY");
于 2015-05-30T18:03:46.097 回答
7

在 IE 11、Chrome、Firefox 上测试

const dt = new Date();
const locale = navigator.languages != undefined ? navigator.languages[0] : navigator.language;
const fullMonth = dt.toLocaleDateString(locale, {month: 'long'});
console.log(fullMonth);

于 2020-08-20T07:57:39.590 回答
6

你可以试试这个:

let d = new Date(),
  t = d.toDateString().split(" ");

console.log(t[2] + " " + t[1] + " " + t[3]);

于 2021-01-05T15:36:25.193 回答
5

如果您使用剑道,也可以这样做。

kendo.toString(dateobject, "MMMM");

以下是来自剑道网站的格式化程序列表:

"d" 呈现月份中的某一天,从 1 到 31。

"dd" 月份中的第几天,从 01 到 31。

"ddd" 星期几的缩写名称。

"dddd" 星期几的全名。

"f" 日期和时间值的十分之一秒。

"ff" 日期和时间值的百分之一秒。

"fff" 日期和时间值中的毫秒数。

"M" 月份,从 1 到 12。

"MM" 月份,从 01 到 12。

“MMM” 月份的缩写名称。

“MMMM”月份的全称。

"h" 小时,使用从 1 到 12 的 12 小时制。

"hh" 小时,使用从 01 到 12 的 12 小时制。

"H" 小时,使用从 1 到 23 的 24 小时制。

"HH" 小时,使用从 01 到 23 的 24 小时制。

"m" 分钟,从 0 到 59。

"mm" 分钟,从 00 到 59。

"s" 第二个,从 0 到 59。

"ss" 第二个,从 00 到 59。

“tt” AM/PM 指示符。

"yy" 年份值的最后两个字符。

"yyyy" 年份全值。

"zzz" 使用格式解析 UTC 日期字符串时的本地时区。

于 2017-04-10T12:49:22.540 回答
4

如果您不想使用外部库,或存储月份名称数组,或者 ECMAScript 国际化 API 由于浏览器兼容性而不够好,您始终可以通过从日期输出:

var now = new Date();
var monthAbbrvName = now.toDateString().substring(4, 7);

这将为您提供缩写的月份名称,例如 Oct。我相信日期会以各种格式出现,具体取决于初始化和您的语言环境,因此请查看toDateString()返回的内容并substring()根据此重新计算您的值。

于 2014-05-28T22:25:54.807 回答
4

最简单最简单的方法。

  1. 将日期转换为字符串。
  2. 用 ' ' 空格分割。
  3. 从数组中选择第二个元素。

   
var now = new Date();
var nowStr = now.toDateString(); 
// "Fri Apr 2020'

var currentMonth = nowStr.split(' '); 
// ['Fri' 'Apr' '2020']

console.log(currentMonth[1]);
// 'Apr'
         

于 2020-04-10T17:34:33.290 回答
4

您可以处理或不翻译成当地语言

  1. 生成值为“2009 年 10 月 11 日”

const objDate = new Date("10/11/2009");
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
if (objDate !== 'Invalid Date' && !isNaN(objDate)) {
  console.log(objDate.getDate() + ' ' + months[objDate.getMonth()] + ' ' + objDate.getFullYear())
}

  1. 用于将月份翻译成本地语言的 ECMAScript 国际化 API(例如:11 octobre)

const convertDate = new Date('10/11/2009')
const lang = 'fr' // de, es, ch 
if (convertDate !== 'Invalid Date' && !isNaN(convertDate)) {
  console.log(convertDate.getDate() + ' ' + convertDate.toLocaleString(lang, {
    month: 'long'
  }))
}

于 2020-05-15T08:22:41.527 回答
3

如果您使用 jQuery,您可能也在使用 jQuery UI,这意味着您可以使用$.datepicker.formatDate()

$.datepicker.setDefaults( $.datepicker.regional[ "nl" ] );   // dutch
$.datepicker.formatDate( "dd MM yy", objDate );
于 2013-05-24T09:54:11.837 回答
3

我的最佳解决方案如下:

       var dateValue = Date();
       var month = dateValue.substring(4,7);
       var date = dateValue.substring(8,10);
       var year = dateValue.substring(20,24);
       var finaldateString = date+"-"+month+"-"+year;
于 2014-08-08T05:25:10.217 回答
3

使用momentjs,只需使用格式符号。

const myDate = new Date()
const shortMonthName = moment(myDate).format('MMM') // Aug
const fullMonthName = moment(myDate).format('MMMM') // August
于 2016-08-04T04:29:06.180 回答
3

对我来说,这是最好的解决方案,

也适用于 TypeScript

const env = process.env.REACT_APP_LOCALE || 'en';

const namedMonthsArray = (index?: number): string[] | string => {
  const months = [];

  for (let month = 0; month <= 11; month++) {
    months.push(
      new Date(new Date('1970-01-01').setMonth(month))
        .toLocaleString(env, {
          month: 'long',
        })
        .toString(),
    );
  }
  if (index) {
    return months[index];
  }
  return months;
};

输出是

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
于 2019-07-29T15:48:28.603 回答
3

也可以这样做:

var x = new Date().toString().split(' ')[1];    // "Jul"
于 2020-07-06T16:11:27.770 回答
2

如果您不想使用时刻并想显示月份名称 -

.config($mdDateLocaleProvider) {
    $mdDateLocaleProvider.formatDate = function(date) {      
      if(date !== null) {
        if(date.getMonthName == undefined) {
          date.getMonthName = function() {
            var monthNames = [ "January", "February", "March", "April", "May", "June", 
            "July", "August", "September", "October", "November", "December" ];
            return monthNames[this.getMonth()];
          }
        }        
        var day = date.getDate();
        var monthIndex = date.getMonth();
        var year = date.getFullYear();
        return day + ' ' + date.getMonthName() + ' ' + year;
      }
    };
  }
于 2016-11-15T10:36:27.140 回答
2

要使用 JavaScript 将日期格式设置为“dd-MMM-yyyy”,请使用以下代码

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

    const d = new Date();
    var dd = String(d.getDate()).padStart(2, '0');
    var mm = String(d.getMonth() + 1).padStart(2, '0');
    var yyyy = d.getFullYear();
    var fullDate = +dd +"-"+ monthNames[d.getMonth()] +"-"+ yyyy;
    document.write("The date is : "+ fullDate);

于 2020-10-27T19:03:41.780 回答
1

将名称存储在数组中并按月份的索引查找。

var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";

document.write("The current month is " + month[d.getMonth()]);

JavaScript getMonth() 方法

于 2009-10-29T12:22:08.157 回答
1

我想出了一个部分解决方案。它使用正则表达式来提取月份和日期名称。但是当我查看区域和语言选项(Windows)时,我意识到不同的文化有不同的格式顺序......也许更好的正则表达式模式可能有用。

function testDateInfo() {
        var months = new Array();
        var days = new Array();
        var workingDate = new Date();
        workingDate.setHours(0, 0, 0, 0);
        workingDate.setDate(1);
        var RE = new RegExp("([a-z]+)","ig");
        //-- get day names 0-6
        for (var i = 0; i < 7; i++) {

            var day = workingDate.getDay();
            //-- will eventually be in order
            if (days[day] == undefined)
                days[day] = workingDate.toLocaleDateString().match(RE)[0];
            workingDate.setDate(workingDate.getDate() + 1);
        }
        //--get month names 0-11
        for (var i = 0; i < 12; i++) {
            workingDate.setMonth(i);
            months.push(workingDate.toLocaleDateString().match(RE)[1]);
        }
        alert(days.join(",") + " \n\r " + months.join(","));
    }
于 2012-09-12T21:35:15.880 回答
0

只是扩展了许多其他优秀的答案——如果你使用的是 jQuery——你可以做类似的事情

$.fn.getMonthName = function(date) {

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

    return monthNames[date.getMonth()];

};

其中date等于var d = new Date(somevalue)。这样做的主要优点是每个@nickf 所说的关于避免全局命名空间。

于 2013-03-09T06:36:18.840 回答
0

要获取月份名称数组:

Date.monthNames = function( ) {
var arrMonth = [],
    dateRef = new Date(),
    year = dateRef.getFullYear();

dateRef.setMonth(0);
while (year == dateRef.getFullYear()) {
    /* push le mois en lettre et passe au mois suivant */
    arrMonth.push( (dateRef.toLocaleString().split(' '))[2] );
    dateRef.setMonth( dateRef.getMonth() + 1);
}

return arrMonth;
}

alert(Date.monthNames().toString());

// -> janvier,février,mars,avril,mai,juin,juillet,août,septembre,octobre,novembre,décembre

http://jsfiddle.net/polinux/qb346/

于 2014-01-24T22:26:25.097 回答
0

只需编写一个简单的包装器toLocaleString

function LocalDate(locale) {
  this.locale = locale;
}

LocalDate.prototype.getMonthName = function(date) {
  return date.toLocaleString(this.locale,{month:"long"});
};

var objDate = new Date("10/11/2009");

var localDate = new LocalDate("en");
console.log(localDate.getMonthName(objDate));

localDate.locale = "ru";
console.log(localDate.getMonthName(objDate));

localDate.locale = "zh";
console.log(localDate.getMonthName(objDate));

于 2018-05-10T16:21:38.030 回答
0

我使用的一个快速破解效果很好:

const monthNumber = 8;
const yearNumber = 2018;
const date = `${['Jan', 'Feb', 'Mar', 'Apr',
  'May', 'Jun', 'Jul', 'Aug',
  'Sep', 'Oct', 'Nov', 'Dec'][monthNumber - 1]
      } ${yearNumber}`;

console.log(date);

于 2018-08-09T05:07:38.253 回答
0

我是通过 DatePipe 完成的。

const datePipe = new DatePipe(this.locale);
datePipe.transform(myDate, 'MMM. y');

您可以像这样在构造函数中注入默认语言环境:

constructor(@Inject(LOCALE_ID) private locale: string){}

来自 Angular https://angular.io/api/common/DatePipe的参考

于 2022-01-31T18:05:28.523 回答