2011-01-10 70 views
1

在時代 是 週五2010年2月12日12點五十五分51秒GMT-0500(EST)難倒JS大紀元皈依

我試圖把它寫成: 月, 12 2010

但我得到:月,10 42087

什我做錯了嗎?

function makeHumanDate(epoch) { 
    var theDate = epoch * 1000 
    var months = new Array(13); 
    months[0] = "January"; 
    months[1] = "February"; 
    months[2] = "March"; 
    months[3] = "April"; 
    months[4] = "May"; 
    months[5] = "June"; 
    months[6] = "July"; 
    months[7] = "August"; 
    months[8] = "September"; 
    months[9] = "October"; 
    months[10] = "November"; 
    months[11] = "December"; 
    var d   = new Date(theDate); 
    var monthnumber = d.getUTCMonth(); 
    var monthname = months[monthnumber]; 
    var monthday = d.getUTCDate(); 
    var year  = d.getFullYear(); 
    if(year < 2000) { year = year + 1900; } 
    var dateString = monthname + 
        ', ' + 
        monthday + 
        ' ' + 
        year; 
    // Goal is: February, 12 2010 
    return dateString; 
} 

我知道它的一些愚蠢的東西,但我被卡住了一段時間。請幫忙。

謝謝!

+0

只是一些不請自來的建議。你可以像這樣`var months = ['January','February','March','April','May','June','July','August','September','十月','十一月','十二月'];` – Hemlock 2011-01-10 20:41:05

回答

3

你不需要通過1000在您的示例代碼乘以epoch - 如果你採取了這一點,它按預期工作:)

一些代碼清理

function makeHumanDate(epoch) { 
    var months = ["January", 
       "February", 
       "March", 
       "April", 
       "May", 
       "June", 
       "July", 
       "August", 
       "September", 
       "October", 
       "November", 
       "December"], 
     d = new Date(epoch), 
     month = months[d.getUTCMonth()], 
     day = d.getUTCDate(), 
     year = d.getFullYear(); 

    // not needed as getFullYear returns the full year in 4 digits 
    //if(year < 2000) year += 1900; 

    return month + ', ' + day + ' ' + year; 
} 
+0

只有我必須改變這個工作是Date(epoch/1)。謝謝你讓我失去知覺。 – 2011-01-10 21:07:37

0

您的代碼很好,但你的輸入被打破。如果我使用http://www.onlineconversion.com/unix_time.htm 我會得到與您相同的結果。

你的時間戳似乎需要1000除法才能讓它回到一個合理的框架,之後我得到正確的結果。