使用JS和Jquery将“月和年”字符串转换为Date对象

时间:2012-06-10 20:31:56

标签: javascript jquery date elapsed

我有两个数组(我是从表中的jQuery创建的),第一个是结束日期,第二个是开始日期。元素是字符串:

["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(),然后进行计算以获得经过的时间,然后使用以下内容将其截断为月份和年份:

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. 如何识别当前元素的姐妹元素,以便我可以避免使用双嵌套循环? (也会在另一个问题中提出这个问题,因为它涉及不同的主题)

  4. 感谢您帮助我,因为我正在尝试制作具有可选属性的交互式简历,并且我包含了一些数据,因此我不必回答所有基本信息给那些冷呼叫的招聘人员。

1 个答案:

答案 0 :(得分: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.