Sort date in Javascript

前端 未结 3 1579

I have retrieve from ajax query a news feed. In this object, there is a date in this format :

Wed, 22 May 2013 08:00:00 GMT

I would like to

相关标签:
3条回答
  • 2021-01-15 01:37
    sorting dates ascending or descending
    times = ["01-09-2013", "01-09-2013", "27-08-2013", "27-08-2013", "28-08-2013", "28-08-2013", "28-08-2013", "28-08-2013", "29-08-2013", "29-08-2013", "30-08-2013", "30-08-2013", "31-08-2013", "31-08-2013"]
    function dmyOrdA(a,b){ return myDate(a) - myDate(b);}
    function dmyOrdD(a,b){ return myDate(b) - myDate(a);}
    function myDate(s){var a=s.split(/-|\//); return new Date(a[2],a[1]-1,a[0]);}
    
    times.sort(dmyOrdA);
    console.log(times)
    
    0 讨论(0)
  • 2021-01-15 01:40

    You may also use a underscore/lodash sortBy

    Here's using underscore js to sort date:

     var log = [{date: '2016-01-16T05:23:38+00:00', other: 'sample'}, 
                {date: '2016-01-13T05:23:38+00:00',other: 'sample'}, 
                {date: '2016-01-15T11:23:38+00:00', other: 'sample'}];
    
      console.log(_.sortBy(log, 'date'));
    
    • http://underscorejs.org/#sortBy
    • https://lodash.com/docs#sortBy
    0 讨论(0)
  • 2021-01-15 01:47

    1) You can't sort objects. The order of the object's keys is arbitrary.

    2) If you want to sort an array by date (and they are already date obects), do the following:

    array.sort ( function (date1, date2){
         return date1 - date2
    });
    

    If you first need to convert them to date objects, do the following (following the data structure according to your comment below):

    array.sort ( function (a, b){
           return new Date(a.pubDate) - new Date(b.pubDate);
    });
    

    Example

    0 讨论(0)
提交回复
热议问题