如何按时间顺序对数组进行排序?

时间:2017-06-18 07:25:05

标签: ios arrays swift sorting date

我想按时间顺序排序数组。我根本不知道如何把自己带到那里......这是阵列:

<?php

namespace App\Jobs;

use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Log;

class SendToAPI extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    private $data = null;
    private static $count = 0;
    /**
    * Create a new job instance.
    *
    * @return void
    */
    public function __construct($data)
    {
      $this->data = $data;
    }

    /**
    * Execute the job.
    *
    * @return void
    */
    public function handle()
    {
       $count = $count + $this->data['file_size'];
       if ($count > 1000)
       {
          // perform action
       }

    } 
 }

我试过了,但那没用......

 [["FM", "TEL", "ID", "2017-06-17 18:16:29 +0000", "TYPE", "inbox"], ["FM", "TEL", "ID", "2017-06-17 18:17:24 +0000", "TYPE", "no", "send"], ["Jm", "TEL", "ID", "2017-06-17 19:25:27 +0000", "TYPE", "no", "send"]]

我想在开头的最近日期,输出应该是这样的:

 str.sort({$0[3].date > $1[3].date})

1 个答案:

答案 0 :(得分:1)

使用dateformatter首先将字符串转换为日期,然后比较它们:

let str = [["FM", "TEL", "ID", "2017-06-17 18:16:29 +0000", "TYPE", "inbox"], ["FM", "TEL", "ID", "2017-06-17 18:17:24 +0000", "TYPE", "no", "send"], ["Jm", "TEL", "ID", "2017-06-17 19:25:27 +0000", "TYPE", "no", "send"]]

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"

let sorted = str.sorted(by: {dateFormatter.date(from: $0[3])!  > dateFormatter.date(from: $1[3])!})