如何从 JavaScript 中的这个日期对象生成月份的名称(例如:Oct/October)?
var objDate = new Date("10/11/2009");
较短的版本:
const monthNames = [“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月” " ];常量 d = 新日期(); document.write("当前月份是" + monthNames[d.getMonth()]);
注意 (2019-03-08) - 我最初在 2009 年写的这个答案已经过时了。请参阅 David Storey's answer 以获得更好的解决方案。
现在可以使用 ECMAScript 国际化 API 执行此操作:
const date = new Date(2009, 10, 10); // 2009-11-10 const month = date.toLocaleString('default', { month: 'long' });控制台日志(月);
'long'
使用月份的全名,'short'
使用简称,'narrow'
使用更小的版本,例如字母语言中的第一个字母。
您可以将区域设置从浏览器的 'default'
更改为您喜欢的任何区域(例如 'en-us'
),它将使用该语言/国家/地区的正确名称。
对于 toLocaleString
api,您每次都必须传入语言环境和选项。如果您要在多个不同的日期使用相同的语言环境信息和格式选项,您可以使用 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} 和 ${month2}`); // 法语和“juin”的当前月份。
有关详细信息,请参阅我在 Internationalization API 上的博文。
这是另一个,支持本地化:)
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: [...]};
Date.locale
是 undefined
。不过,对于其他 JS 实现来说,这是一个很好的答案!
我衷心推荐 moment.js 库中的 format
函数,您可以像这样使用它:
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”
除了一长串其他功能之外,它还具有强大的 support for internationalization。
Luxon
和 date-fns
,但又是 wide browser support for the Internationalization API nowadays。
如果您不介意扩展 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 对象。
如果我们需要传递我们的输入,那么我们需要使用以下方式
输入:'2020-12-28'
代码:
new Date('2020-12-28').toLocaleString('en-us',{month:'short', year:'numeric'})
输出:“2020 年 12 月”
'en-us'
吗?
您可以简单地使用 Date.toLocaleDateString() 并将所需的日期解析为参数
常量事件 = 新日期(日期.UTC(2012, 11, 20, 3, 0, 0));常量选项 = { 年:“数字”,月:“短”,日:“数字”}; console.log(event.toLocaleDateString('de-DE', options)); // 预期输出:Donnerstag,2012 年 12 月 20 日 console.log(event.toLocaleDateString('en-US', options)); // 美国格式 // 如果你只想要月份 console.log(event.toLocaleDateString(undefined, { month: 'short'})); console.log(event.toLocaleDateString(undefined, { month: 'long'}));
您可以在 Firefox documentation 中找到更多信息
如果你赶时间......那么你去!
const date = new Date(Date.now());
date.toLocaleString('en-US', {month: 'short'}); // {month:'long'}
预期输出:"Apr"
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();
document.write(new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}))
new Date().toLocaleString('he-il',{month:'long', year:'numeric', day:'numeric', hour: 'numeric', minute:'numeric', second: 'numeric'});
日期对象的一些常见的简单过程可以通过这个来完成。
var monthNames = [“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月” " ]; var monthShortNames = [“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月” " ];函数 dateFormat1(d) { var t = new Date(d);返回 t.getDate() + ' ' + monthNames[t.getMonth()] + ', ' + t.getFullYear(); } 函数 dateFormat2(d) { var t = new Date(d);返回 t.getDate() + ' ' + monthShortNames[t.getMonth()] + ', ' + t.getFullYear(); } console.log(dateFormat1(new Date())) console.log(dateFormat2(new Date()))
或者您可以制作日期原型,例如
Date.prototype.getMonthName = function() { var monthNames = [“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”,“八月”,“九月”, “十月”、“十一月”、“十二月”];返回月份名称[this.getMonth()]; } Date.prototype.getFormatDate = function() { var monthNames = [“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月” 、“十月”、“十一月”、“十二月”];返回 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
您可以使用 datejs 来执行此操作。检查 FormatSpecifiers,MMMM 为您提供月份名称:
var objDate = new Date("10/11/2009");
document.write(objDate.toString("MMMM"));
datejs 将其本地化为 150 多个语言环境! See here
尝试:
var objDate = new Date("10/11/2009");
var strDate =
objDate.toLocaleString("en", { day: "numeric" }) + ' ' +
objDate.toLocaleString("en", { month: "long" }) + ' ' +
objDate.toLocaleString("en", { year: "numeric"});
另一种格式化日期的方法
new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}) //output: "May 21, 2019"
这是一种不依赖硬编码数组并支持多个语言环境的方法。
如果你需要一个完整的数组:
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 上需要进行一些修改,因为它会返回整个日期。
toLocaleString
除了声明包含所有月份名称的数组然后用索引指向之外,我们还可以将它写成更短的版本,如下所示:
var objDate = new Date().toLocaleString("en-us", { month: "long" }); // result: August
var objDate = new Date().toLocaleString("en-us", { month: "short" }); // result: Aug
MAY 1, 2015 AT 12:00:00 AM GMT-4
(使用 { month: "long" }
参数时)
new Date().toLocaleString(navigator.language, { month: "short" })
获取默认值
不幸的是,提取月份名称的最佳方法是使用 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'
最简单最简单的方法:
const dateStr = new Date(2020, 03, 10).toDateString(); // 'Fri Apr 10 2020' const dateStrArr = dateStr.split(' '); // ['Fri', 'Apr', '10', '2020'] console.log(dateStrArr[1]); // '四月'
将日期转换为字符串。用 ' ' 空格分割。从数组中选择第二个元素。
您可以使用几种可用的日期格式化程序之一。由于这属于 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 上还有更多
现在的自然格式是使用 Moment.js。
以字符串格式获取月份的方法在 Moment.js 中非常简单,无需在代码中硬编码月份名称:以月份名称格式和全年(2015 年 5 月)获取当前月份和年份:
moment(new Date).format("MMMM YYYY");
Luxon
和 date-fns
,但又是 wide browser support for the Internationalization API nowadays。
在 IE 11、Chrome、Firefox 上测试
常量 dt = 新日期(); const locale = navigator.languages != undefined ? navigator.languages[0] : navigator.language; const fullMonth = dt.toLocaleDateString(locale, {month: 'long'}); console.log(fullMonth);
你可以试试这个:
让 d = new Date(), t = d.toDateString().split(" ");控制台.log(t[2] + " " + t[1] + " " + t[3]);
如果您使用剑道,也可以这样做。
kendo.toString(dateobject, "MMMM");
以下是来自 kendo site 的格式化程序列表:
"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 日期字符串时的本地时区。
如果您不想使用外部库,或存储月份名称数组,或者 ECMAScript 国际化 API 由于浏览器兼容性而不够好,您始终可以通过从日期输出:
var now = new Date();
var monthAbbrvName = now.toDateString().substring(4, 7);
这将为您提供缩写的月份名称,例如 Oct。我相信日期会以各种格式出现,具体取决于初始化和您的语言环境,因此请查看 toDateString()
返回的内容并根据此重新计算您的 substring()
值.
您可以处理或不翻译成当地语言
生成值为“2009 年 10 月 11 日”
const objDate = new Date("10/11/2009"); const 月 = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec '] if (objDate !== '无效日期' && !isNaN(objDate)) { console.log(objDate.getDate() + ' ' + 月[objDate.getMonth()] + ' ' + objDate.getFullYear() ) }
用于将月份翻译成本地语言的 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' })) }
也可以这样做:
var x = new Date().toString().split(' ')[1]; // "Jul"
如果您使用 jQuery,那么您可能也在使用 jQuery UI,这意味着您可以使用 $.datepicker.formatDate()。
$.datepicker.setDefaults( $.datepicker.regional[ "nl" ] ); // dutch
$.datepicker.formatDate( "dd MM yy", objDate );
我的最佳解决方案如下:
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;
const myDate = new Date()
const shortMonthName = moment(myDate).format('MMM') // Aug
const fullMonthName = moment(myDate).format('MMMM') // August
moment
是一个 very 大型库,并且为此太过分了。现代的替代品包括 Luxon
和 date-fns
,但又是 wide browser support for the Internationalization API nowadays。
对我来说,这是最好的解决方案,
也适用于 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"]
不定期副业成功案例分享
new Date()
返回Tue Sep 06 2011 20:02:25 GMT+0200 (CEST)
这显然意味着 Date 对象已经具有所有这些内部定义的(月份和星期几名称)它不是公开的,所以我们必须再次输入它。 :(String#split
与toString
或toDateString
一起使用。