jquery - How to sort dates by asending order. Dates are like dd/mm/yyyy (31/12/2015) or (dd-MMM-yyyy) format -
i have scenario need sort dates different format dd/mm/yyyy (31/12/2015)
, mm/dd/yyyy (12/31/2015)
.
for mm/dd/yyyy (12/31/2015)
using sortedkey = sortedkey.sort(function(a,b) { return - b;})
how can sort format mm/dd/yyyy
javascript not work dates in dd/mm/yyyy
format.
if had dates in mm/dd/yyyy
format, able convert strings date
, compare:
var arr = ['01-01-2015', '03-03-2015', '07-30-2015', '12-30-2014']; // mm-dd-yyyy arr.sort(function(a, b) { var adate = new date(a); var bdate = new date(b); return (adate < bdate ? -1 : 1); }); document.write(arr.join("<br/>"));
the best way solve problem change format of dates.
however, if cannot change format of dates, can use hacks parsing using regular expressions:
function parse_ddmmyyyy(str) // example: str = '07-30-2015' { var numbers = str.match(/\d+/g); // numbers [7,30,2015] return new date(numbers[2], numbers[1]-1, numbers[0]); // new date(2015, 6, 30) } // dd-mm-yyyy (dd/mm/yyyy) var arr = ['01-01-2015', '03-03-2015', '30-07-2015', '30/12/2014', '18/11/2016', '03-11-2014', '02/01/2015']; arr.sort(function(a, b) { var adate = parse_ddmmyyyy(a); var bdate = parse_ddmmyyyy(b); return (adate < bdate ? -1 : 1); }); document.write(arr.join("<br/>"));
this work both dd-mm-yyyy
, dd/mm/yyyy
, mixed.
Comments
Post a Comment