arrays - how to sort milatry format date in javascript -
i want sort date in ascending order in javascript function.i having date in following format 3/4/2014 1300
im having follwing array contains date
categoriesdata.push(recorddate); categoriesdata.sort(function (a, b) { var key1 = a.recorddate; var key2 = b.recorddate; if (key1 < key2) { return -1; } else if (key1 == key2) { return 0; } else { return 1; } })
categoriesdata have following record
3/4/2014 1300 2/4/2014 0000 1/31/2014 1030
now want sort these record in such way following output
1/31/2014 1030 2/4/2014 0000 3/4/2014 1300
you have split date string , parts using regex
or simple split
var date = "1/31/2014 1030".split(" "); var day = parseint(date[0].split["/"][0], 10); var month = parseint(date[0].split["/"][1], 10) - 1; var year = parseint(date[0].split["/"][2], 10); var hours = parseint(date[1].slice(0,2), 10); var minutes = parseint(date[1].slice(2,4), 10);
then create date
objects them in javascript.
var dateobj = new date(year, month, day, hour);
then convert dates compared "milliseconds since beginning"
var milliseconds1 = date.parse(dateobj)
similarly convert both dates compared in milliseconds, have 2 numbers can compared
incorporate idea sort function.
categoriesdata.push(recorddate); categoriesdata.sort(function (a, b) { var key1 = a.recorddate; var key2 = b.recorddate; var gettimestamp = function (datestring) { var date = datestring.split(" "); var day = parseint(date[0].split["/"][0], 10); var month = parseint(date[0].split["/"][1], 10) - 1; var year = parseint(date[0].split["/"][2], 10); var hours = parseint(date[1].slice(0, 2), 10); var minutes = parseint(date[1].slice(2, 4), 10); return date.parse(new date(year, month, day, hour)); } key1 = gettimestamp(key1); key2 = gettimestamp(key2); if (key1 < key2) { return -1; } else if (key1 == key2) { return 0; } else { return 1; } })
Comments
Post a Comment