2012-06-10 57 views
1

我有兩個數組(我使用jQuery從表中創建它們),第一個是結束日期,第二個是開始日期。這些元素都是字符串:使用JS和JQuery將'Month和Year'字符串轉換爲Date對象

["June, 2012", "June, 2012", "August, 2011", "April, 2013", "August, 2010", "August, 2010", "April, 2013", "April, 2012", "April, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012"]

["November, 2011", "April, 2012", "May, 2008", "May, 2007", "November, 2007", "May, 2007", "June, 2006", "June, 2007", "April, 2006", "January, 2008", "April, 2001", "April, 2001", "April, 2006", "April, 1998", "April, 1998", "September, 2008", "August, 2010", "August, 2009", "August, 2010", "August, 2009", "August, 2010", "August, 2010", "August, 2010", "January, 1997", "January, 1997", "January, 2010", "January, 2007", "April, 2010"]

我試圖讓每一組指數之間的時間。我會認爲我必須將這些字符串轉換爲Date對象date()然後執行計算來獲得所經過的時間,然後就在一個月和一年使用它是這樣的截斷:

function convertDate(passedDate) { 
    var m = new Array(7); 
    var y = passedDate.getFullYear(); 
    m[0] = "January"; 
    m[1] = "February"; 
    m[2] = "March"; 
    m[3] = "April"; 
    m[4] = "May"; 
    m[5] = "June"; 
    m[6] = "July"; 
    m[7] = "August"; 
    m[8] = "September"; 
    m[9] = "October"; 
    m[10] = "November"; 
    m[11] = "December"; 
    return m[passedDate.getMonth()] + "months and " + y + " years; 
}; 

這裏是fiddle這裏是我的問題:

  1. 反正有沒有做到這一點,而不將其更改爲約會對象,因爲我不感興趣的日子或時間?

  2. 是否有另一種方法,你會建議,而不是嘗試將日期轉換爲經過日期數學公式,然後轉換回字符串?

  3. 我將如何識別當前元素的姐妹元素,以便我可以避免使用雙重嵌套循環? (也將在不同的問題,問這個,因爲它解決了一個不同的主題)

謝謝你幫我,我試圖與可選屬性的互動簡歷,我包括一些數據,以便我不需要回答所有冷酷呼叫的招聘人員的基本信息。

回答

6

真的,所有你需要的是從月份名稱到數字的地圖。你可以建立一個這樣的:

var monthNames = [ "January", "February", "March", "April", 
        "May",  "June",  "July",  "August", 
        "September", "October", "November", "December" ] 
var monthNumber = {} 
for (var i=0; i<monthNames.length; ++i) { 
    monthNumber[monthNames[i]] = i; 
} 

現在你有,例如,monthNumber['October'] == 9。然後你可以把你的一個字符串成月數和年。如果您然後將其轉換爲絕對月份數(年* 12 +月),您可以減去以獲取經過的月份。

function stringToMonthNumber(monthYear) { 
    var parts = monthYear.split(/\s*,\s*/) 
    var month = monthNumber[parts[0]] 
    var year = parts[1] - 1 
    return year * 12 + month 
} 

function elapsedMonths(startString, endString) { 
    return stringToMonthNumber(endString) - stringToMonthNumber(startString) 
} 

那麼這個:

elapsedMonths("November, 2011", "June, 2012") 

回報7.

相關問題