SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Jun 2010
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    javascript Date sorting(Urgent help needed)

    Consider I have an array with dates : {11.08.2010, 18.09.2010, 23.09.2010, 30.08.2010}

    I need to sort this array so that all the dates in August come before September i.e correct date array. So the final array should look like this:

    {11.08.2010, 30.08.2010, 18.09.2010, 23.09.2010}.

    Can someone please send me the code to do this. It is really urgent and I need help in this issue.

    Thanks in advance

  2. #2
    SitePoint Zealot
    Join Date
    May 2009
    Location
    Netherlands
    Posts
    189
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you store dates in ISO 8601 format, it would make it much simpler.
    Code:
    var dates = [20100811, 20100918, 20100923, 20100830]; 
    dates.sort();
    alert(dates[0].toString().replace(/(\d{4})(\d{2})(\d{2})/, "$3.$2.$1"));

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    // You need to test the year, year and month, or year, month and date of each item,
    // sorting on the first difference found.
    // parseInt is used for clients that think '08' is 10....

    Code:
    var days= ['11.08.2010','18.09.2010',
    '23.09.2010','30.08.2010'];
    
    days.sort(function(a, b){
    	var aa= a.split('.'), bb= b.split('.');
    	if(aa[2]!= bb[2]) return aa[2]-bb[2];
    	if(aa[1]!= bb[1]){
               return parseInt(aa[1], 10)-parseInt(bb[1], 10);
            }
    	return parseInt(aa[0], 10)-parseInt(bb[0], 10);
    });
    
    
    alert(days.join('\n'))
    /* value:
    11.08.2010
    30.08.2010
    18.09.2010
    23.09.2010
    */


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •