简体   繁体   English

获取哪个日期范围是Javascript中的日期

[英]Get in which range of dates is a date in Javascript

I have got an array with one or more arrays: 我有一个带有一个或多个数组的数组:

For example, with one array: 例如,使用一个数组:

var array1 = [['2','name','surname','2014-01-01']];

Or with more than one(It is dynamic, sometimes it comes with 1 other with 2, with 3,... but always with the date ordered 'asc'). 或不止一个(它是动态的,有时它带有1个其他的,2个,3个,...,但始终带有按顺序'asc'排列的日期)。

var array1 = [['2','name','surname','2014-01-01'],['2','name1','surname1','2014-02-02'],['2','name2','surname2','2014-03-03'],['2','name3','surname3','2014-04-02']];

Then I have got a date: 然后我有个约会:

var givenDate="2014-03-28";

I want to get the array where givenDate is in the range. 我想得到给定日期在范围内的数组。 I want the beginning array. 我想要开始数组。 In this case the 3rd array: ['2','name2','surname2','2014-03-03'] 在这种情况下,第三个数组: ['2','name2','surname2','2014-03-03']

I dont know which is the most effective way. 我不知道哪种方法最有效。

Thanks 谢谢

EDIT: This will either return an array with an exact match of the givendate. 编辑:这将返回一个与给定日期完全匹配的数组。 If no exact match is found it will return the array with the date closest to the givendate: 如果未找到完全匹配的内容,它将返回日期最接近给定日期的数组:

var array1 = [['2','name','surname','2014-01-01'],['2','name1','surname1','2014-02-02'],['2','name2','surname2','2014-03-03'],['2','name3','surname3','2014-04-02']];
var givenDate = '2014-02-12';
var key = false;
var index;
var differences = [];
for( index=0; index < array1.length; ++index ){
    if( array1[index][3] == givenDate ){
        key = index;
    }       
}
if( !key ){
    for( index=0; index < array1.length; ++index ){
        difference = givenDate.replace(/-/g, '') - array1[index][3].replace(/-/g, '')
        differences[difference] = [];
        differences[difference]['key'] = index;
    }   
}
if( key ){
    alert( 'Exact match for given date is found and holds key: ' + key );
    alert( 'Resulting array: ' + array1[key] );         
}
if( differences.length > 0 ){
    alert( 'Found a nearest key' );
    var firstKey = getFirstKey(differences);
    alert( 'Resulting Array: ' + array1[differences[firstKey]['key']] );
}
function getFirstKey( data ) {
    for (elem in data ) 
        return elem;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM