从日期获取月份名称

发布于 2024-08-09 11:55:15 字数 115 浏览 10 评论 0原文

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

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

How can I generate the name of the month (e.g: Oct/October) from this date object in JavaScript?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

┈┾☆殇 2024-08-16 11:55:15

现在可以使用 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".

有关详细信息,请参阅我关于国际化 API 的博客文章。

It is now possible to do this with the ECMAScript Internationalization API:

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

'long' uses the full name of the month, 'short' for the short name, and 'narrow' for a more minimal version, such as the first letter in alphabetical languages.

You can change the locale from browser's 'default' to any that you please (e.g. 'en-us'), and it will use the right name for that language/country.

With toLocaleStringapi you have to pass in the locale and options each time. If you are going do use the same locale info and formatting options on multiple different dates, you can use Intl.DateTimeFormat instead:

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".

For more information see my blog post on the Internationalization API.

夜还是长夜 2024-08-16 11:55:15

较短的版本:

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 的回答以获得更好的解决方案。

Shorter version:

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()]);

Note (2019-03-08) - This answer by me which I originally wrote in 2009 is outdated. See David Storey's answer for a better solution.

贵在坚持 2024-08-16 11:55:15

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

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: [...]};

Here's another one, with support for localization :)

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']
    }
};

you can then easily add support for other languages:

Date.locale.fr = {month_names: [...]};
黑凤梨 2024-08-16 11:55:15

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

input: '2020-12-28'

Code:

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

Output: " 2020 年 12 月”

If we need to pass our input then we need to use the following way

input: '2020-12-28'

Code:

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

Output: "Dec 2020"

命比纸薄 2024-08-16 11:55:15

我衷心推荐来自 format 函数href="http://momentjs.com" rel="noreferrer">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”,如果你需要月份的全名

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

I heartily recommend the format function from, the moment.js library, which you can use like this:

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

Use "MMMM" instead of "MMM" if you need the full name of the month

In addition to a lengthy list of other features, it has strong support for internationalization.

甜中书 2024-08-16 11:55:15

如果您不介意扩展 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 日期对象。

If you don't mind extending the Date prototype (and there are some good reasons to not want to do this), you can actually come up with a very easy method:

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"

These functions will then apply to all javascript Date objects.

虫児飞 2024-08-16 11:55:15

如果您赶时间...那就来吧!

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

预期输出:“Apr”

If you are in hurry...then here you go!

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

Expected Output: "Apr"

倾城花音 2024-08-16 11:55:15

您可以简单地使用 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 文档

You could just simply use Date.toLocaleDateString() and parse the date wanted as parameter

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'}));

You can find more information in the Firefox documentation

亚希 2024-08-16 11:55:15
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();
Date.prototype.getMonthName = function() {
    var monthNames = [ "January", "February", "March", "April", "May", "June", 
                       "July", "August", "September", "October", "November", "December" ];
    return monthNames[this.getMonth()];
}

It can be used as

var month_Name = new Date().getMonthName();
云醉月微眠 2024-08-16 11:55:15
document.write(new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}))

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

山人契 2024-08-16 11:55:15

另一种格式化日期的方法

new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}) //output: "May 21, 2019"

Another way to format date

new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}) //output: "May 21, 2019"
浮华 2024-08-16 11:55:15

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

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(); <代码># 2017 年 3 月 16 日

Some common easy process from date object can be done by this.

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()))

Or you can make date prototype like

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())

Ex:

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

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

谎言月老 2024-08-16 11:55:15

您可以使用 datejs 来执行此操作。检查 FormatSpecifiers,MMMM 为您提供月份的名称:

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

并且 datejs 已将其本地化为超过 150 个地点! 查看此处

You might use datejs to do that. Check the FormatSpecifiers, MMMM gives you the month's name:

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

And datejs got that localized for more than 150 locales! See here

云裳 2024-08-16 11:55:15

尝试:

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

var strDate =
    objDate.toLocaleString("en", { day: "numeric" }) + ' ' +
    objDate.toLocaleString("en", { month: "long"  }) + ' ' +
    objDate.toLocaleString("en", { year: "numeric"});

Try:

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

var strDate =
    objDate.toLocaleString("en", { day: "numeric" }) + ' ' +
    objDate.toLocaleString("en", { month: "long"  }) + ' ' +
    objDate.toLocaleString("en", { year: "numeric"});
笑梦风尘 2024-08-16 11:55:15

我们也可以将其写成更短的版本,如下所示,而不是声明包含所有月份名称的数组然后用索引指向:

var objDate = new Date().toLocaleString("en-us", { month: "long" }); // result: August
var objDate = new Date().toLocaleString("en-us", { month: "short" }); // result: Aug

Instead of declaring array which hold all the month name and then pointing with an index, we can also write it in a shorter version as below:

var objDate = new Date().toLocaleString("en-us", { month: "long" }); // result: August
var objDate = new Date().toLocaleString("en-us", { month: "short" }); // result: Aug
盗心人 2024-08-16 11:55:15

这是一种不依赖于硬编码数组并支持多个区域设置的方法。

如果您需要整个数组:

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 上需要进行一些修改,因为它返回整个日期。

Here's a way that does not depend on a hard-coded array and supports multiple locales.

If you need a whole array:

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;
};

Usage:

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

If you need only a selected month (faster):

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

Usage:

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

Tested and works fine on Chrome and IE 11. On mozilla some modifications are needed, because it returns the whole date.

傲影 2024-08-16 11:55:15

最简单、最简单的方法:

const dateStr = new Date(2020, 03, 10).toDateString(); // 'Fri Apr 10 2020'
const dateStrArr = dateStr.split(' '); // ['Fri', 'Apr', '10', '2020']
console.log(dateStrArr[1]); // 'Apr'

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

The easiest and simplest way:

const dateStr = new Date(2020, 03, 10).toDateString(); // 'Fri Apr 10 2020'
const dateStrArr = dateStr.split(' '); // ['Fri', 'Apr', '10', '2020']
console.log(dateStrArr[1]); // 'Apr'

  1. Convert the date to a string.
  2. Split by ' ' a space.
  3. Select second element of from array.
心凉 2024-08-16 11:55:15

快速又简单

new Date("10/11/2009").toLocaleString("en-US", { month: "long" })
// 'October'

quick and easy

new Date("10/11/2009").toLocaleString("en-US", { month: "long" })
// 'October'
难理解 2024-08-16 11:55:15

不幸的是,提取月份名称的最佳方法是从 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'

Unfortunately the best way to extract the month name is from the UTCString representation:

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'
︶葆Ⅱㄣ 2024-08-16 11:55:15

在 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);

Tested on 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);

纸短情长 2024-08-16 11:55:15

您可以使用多种可用的日期格式化程序之一。由于这属于 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

You can use one of several available Date formatters. Since this falls within the JavaScript specification, it will be available in both browser and server-side modes.

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

e.g.

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

There are more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

娇女薄笑 2024-08-16 11:55:15

如今,自然的格式是使用 Moment.js。

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

  moment(new Date).format("MMMM YYYY");

The natural format this days is to use Moment.js.

The way to get the month in a string format , is very simple in Moment.js no need to hard code the month names in your code:
To get the current month and year in month name format and full year (May 2015) :

  moment(new Date).format("MMMM YYYY");
美人如玉 2024-08-16 11:55:15

你可以试试这个:

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

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

You can try this:

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

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

爱,才寂寞 2024-08-16 11:55:15

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

kendo.toString(dateobject, "MMMM");

以下是来自 kendo 站点 的格式化程序列表:

“d”呈现一月中的第几天,从 1 到 31。

“dd”一月中的某一天,从 01 到 31。

“ddd”星期几的缩写名称。

“dddd”星期几的全名。

“f”日期和时间值中的十分之一秒。

“ff”日期和时间值中的百分之一秒。

“fff”日期和时间值中的毫秒。

“M”月份,从 1 到 12。

“MM”月份,从 01 到 12。

“MMM”月份的缩写名称。

“MMMM”月份的全名。

“h”小时,使用 12 小时制,从 1 到 12。

“hh”小时,使用 12 小时制,从 01 到 12。

“H”小时,使用 24 小时制,从 1 到 23。

“HH”小时,使用 24 小时制,从 01 到 23。

“m”分钟,从 0 到 59。

“mm”分钟,从 00 到 59。

“s”第二个,从 0 到 59。

“ss”第二个,从 00 到 59。

“tt”AM/PM 指示符。

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

“yyyy”年份完整值。

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

This can be also done if you are using kendo.

kendo.toString(dateobject, "MMMM");

Here are list of formatters from kendo site:

"d" Renders the day of the month, from 1 through 31.

"dd" The day of the month, from 01 through 31.

"ddd" The abbreviated name of the day of the week.

"dddd" The full name of the day of the week.

"f" The tenths of a second in a date and time value.

"ff" The hundredths of a second in a date and time value.

"fff" The milliseconds in a date and time value.

"M" The month, from 1 through 12.

"MM" The month, from 01 through 12.

"MMM" The abbreviated name of the month.

"MMMM" The full name of the month.

"h" The hour, using a 12-hour clock from 1 to 12.

"hh" The hour, using a 12-hour clock from 01 to 12.

"H" The hour, using a 24-hour clock from 1 to 23.

"HH" The hour, using a 24-hour clock from 01 to 23.

"m" The minute, from 0 through 59.

"mm" The minute, from 00 through 59.

"s" The second, from 0 through 59.

"ss" The second, from 00 through 59.

"tt" The AM/PM designator.

"yy" The last two characters from the year value.

"yyyy" The year full value.

"zzz" The local timezone when using formats to parse UTC date strings.

雨落星ぅ辰 2024-08-16 11:55:15

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

对于 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"]

For me this is best solution is,

for TypeScript as well

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;
};

Output is

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
溺ぐ爱和你が 2024-08-16 11:55:15

您可以处理或不翻译为本地语言

  1. 生成值“11 Oct 2009”
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 将月份翻译为本地语言(例如:10 月 11 日)
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'
  }))
}

You can handle with or without translating to the local language

  1. Generates value as "11 Oct 2009"

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. The ECMAScript Internationalization API to translate month to local language (eg: 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'
  }))
}

顾冷 2024-08-16 11:55:15

也可以按如下方式完成:

var x = new Date().toString().split(' ')[1];    // "Jul"

It can be done as follows too:

var x = new Date().toString().split(' ')[1];    // "Jul"
¢好甜 2024-08-16 11:55:15

这是一个函数,您传入 1 到 12,然后返回完整的月份名称,例如“January”或“July”

    function getMonthName(monthNumber) {
      return new Date('1999-' + monthNumber + '-15').toLocaleString('en-us', { month: 'long' })
    }

Here's a function where you pass in 1 to 12, and returns back the full month name such as 'January' or 'July'

    function getMonthName(monthNumber) {
      return new Date('1999-' + monthNumber + '-15').toLocaleString('en-us', { month: 'long' })
    }
像极了他 2024-08-16 11:55:15

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

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

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

If you don't want to use an external library, or store an array of month names, or if the ECMAScript Internationalization API is not good enough because of browser compatibility you can always do it the old-fashioned way by extracting the info from the date output:

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

This would give you the abbreviated month name, e.g. Oct. I believe the date will come in all sorts of formats depending on the initialization and your locale so take a look at what toDateString() returns and recalculate your substring() values based on that.

最舍不得你 2024-08-16 11:55:15

要使用 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);

To get Date formatted as "dd-MMM-yyyy" using JavaScript use the below code

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);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文