本文介紹了使用原生 JS 獲取本地化月份名稱的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
可以使用本機 javascript.
var objDate = new Date("10/11/2009"),
locale = "en-us",
month = objDate.toLocaleString(locale, { month: "long" });
但這只會獲取給定日期的月份數.我只想獲取與月份編號相對應的月份名稱.例如,如果我執行 getMonth(2)
,它將返回 February
.如何使用本機 javascript 實現 getMonth
(沒有像 moment
這樣的庫)?
But this only gets the month number for a given date. I'd simply like to get the month name corresponding to a month number. For example, if I do getMonth(2)
it would return February
. How can I implement getMonth
using native javascript(no libraries like moment
)?
推薦答案
你已經很接近了:
var getMonth = function(idx) {
var objDate = new Date();
objDate.setDate(1);
objDate.setMonth(idx-1);
var locale = "en-us",
month = objDate.toLocaleString(locale, { month: "long" });
return month;
}
console.log(getMonth(1));
console.log(getMonth(12));
這篇關于使用原生 JS 獲取本地化月份名稱的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!