2016-07-27 87 views
1

什麼是生成日期的最佳方式,例如:2016年7月27日4:53:18在JavaScript中?Javascript - 生成日期的最佳方式,如2016年7月27日4:53:18

我想過連接字符串,但我很難找到如何獲得特定縮略格式的月份(七月)。

在此先感謝! :)

+1

您是否嘗試過內置'Date'對象? – gcampbell

+0

我認爲連接是去這裏的最佳方式! –

+0

@gcampbell:是的,但似乎有一個getMonth()方法,該方法將月份返回爲int(即:1月份爲2),但我正在尋找一個縮寫的月份,例如Jul,並且我不確定如何得到那個 – Rose

回答

4

對於瀏覽器支持Date.prototype.toLocaleString()

var month = []; 
 

 
for(var n = 0; n < 12; n++) { 
 
    month[n] = (new Date(0, n + 1)).toLocaleString("en", {month: "short"}); 
 
} 
 

 
console.log(month);

或者與Intl.DateTimeFormat()

var month = [], 
 
    intl = new Intl.DateTimeFormat("en", {month: "short"}); 
 

 
for(n = 0; n < 12; n++) { 
 
    month[n] = intl.format(new Date(0, n + 1)); 
 
} 
 

 
console.log(month);

注:new Date(0, n + 1)在1900年,這是因爲OK,我們只關心這裏每月產生的日期。

最後,這應該是非常接近最終預期輸出:

var intl = new Intl.DateTimeFormat(
 
    "en-US", 
 
    { 
 
    month : "short", 
 
    day : "numeric", 
 
    year : "numeric", 
 
    hour : "numeric", 
 
    minute : "numeric", 
 
    second : "numeric" 
 
    } 
 
); 
 

 
console.log(intl.format(Date.now()));

+0

@ Arnauld獲得它:謝謝!我不知道你可以這樣做:)太棒了。 – Rose

0

要獲得縮寫的月份,你可以使用下面的代碼片段:

var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", 
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" 
]; 

function monthShortFormat(d){ 
    var t = new Date(d); 
    return t.getDate()+' '+monthShortNames[t.getMonth()]+', '+t.getFullYear(); 
} 
相關問題