开发者

How to find minimum date from 3 dates using javascript function?

I want to find minimum date from 3 dates (8/1/2011,6/1/2011,7/1开发者_StackOverflow中文版/2011) format is (mm/dd/yyyy) using java script.


Convert the dates to int, use Math.min to find the smallest:

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


Untested code, but you should get the idea!

// 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));


/**
 * 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')

See Date for details. If you are a jQuery UI user, you might find their date parsing method helpful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜