2011-04-20 44 views

回答

2

未经测试的代码,但你应该明白了吧!

// Initialise an array of dates, with correct values 
// You want 3 dates, so put them in here 
var MyDates= New Array('15/10/2000','28/05/1999','17/09/2005'); 

// A function that takes an array of dates as its input 
// and returns the smallest (earliest) date 
// MUST take at LEAST 2 dates or will throw an error! 
function GetSmallestDate(DateArray){ 

    var SmallestDate = new Date(DateArray[0]); 
    for(var i = 1; i < DateArray.length; i++) 
    { 
     var TempDate = new Date(DateArray[i]); 
     if(TempDate < SmallestDate) 
      SmallestDate = TempDate ; 
    } 
    return SmallestDate ; 
} 

// Call the function! 
alert(GetSmallestDate(MyDates)); 
+1

你不能比较字符串这样,你需要'Date'对象或至少串'YYYY/MM/DD'格式。 – 2011-04-20 10:22:54

+0

@Marcel谢谢,我已经改变了,现在应该工作,这一切都未经测试,虽然 – 2011-04-20 10:49:41

+0

这是好了很多,但仍然不是很强劲:如果你给'Date'一个字符串,你不得不拥有一个实现相关的方法[日期解析](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse);你最好使用像Rudie使用的方法,在这里你提供'Date'三个参数(转换为数字)。 – 2011-04-20 10:54:09

1
/** 
* Return the timestamp of a MM/DD/YYYY date 
*/ 
function getTime(date) { 
    var tmp = date.split('/'); 
    var d = new Date(tmp[2], parseInt(tmp[0])-1, tmp[1]); 
    return d.getTime(); 
} 
// then return the output: getTime('6/7/2000') < getTime('6/7/2001') 

详见Date。如果你是一个jQuery UI用户,你可能会发现他们的date parsing method有帮助。

+0

使用'Math.min.apply(null,dates)'来获得最小时间。 – Rudie 2011-04-20 10:31:44

+0

@Marcel Korpel谢谢,纠正。 – Boldewyn 2011-04-20 12:10:22

3

转换日期为int,使用Math.min寻找最小:

var dates = ['8/1/2011', '6/1/2011', '7/1/2011']; // dates 
dates = dates.map(function(d) { 
    d=d.split('/'); 
    return new Date(d[2], parseInt(d[0])-1, d[1]).getTime(); 
}); // convert 
var minDate = new Date(Math.min.apply(null, dates)); // smallest > Date 
+0

+1使用'apply',的确比我的解决方案更加整洁。但是请记住,'Array.map'在许多浏览器中都不支持,但是(没有IE <9)。 – 2011-04-20 10:38:59