1

我有两个数组(我从一个表中用 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 对象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;  
};

这是小提琴,这是我的问题:

  1. 因为我对日期或时间不感兴趣,所以无论如何都可以在不将其更改为日期对象的情况下执行此操作?

  2. 除了尝试将经过日期数学公式转换为日期,然后再转换回字符串之外,您是否会建议另一种方法?

  3. 如何识别当前元素的姐妹元素,以便避免使用双嵌套循环?(也会在不同的问题中提出这个问题,因为它涉及不同的主题)

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

4

1 回答 1

7

真的,您所需要的只是一张从月份名称到数字的地图。您可以像这样构建一个:

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。

于 2012-06-10T21:00:17.797 回答