title: Swift sort core data by date (not just time)
body: <p>I'm building a app in Swift using core data. I'm using task Entities with due attribute that is a Date. I need to sort the tasks according to this due date.</p>
  
  <p>I tried using a NSSortDescriptor with key due</p>
  
  <pre><code>NSSortDescriptor.init(key: "due", ascending: false)
  </code></pre>
  
  <p><strong>Issue:</strong></p>
  
  <p>It sorts my data by time only - not considering the day/month/year</p>
  
  <p>here is the data I got from my fetch request:</p>
  
  <pre><code>Optional(2017-02-06 03:29:18 +0000)
  Optional(2017-02-08 03:29:27 +0000)
  Optional(2017-02-07 03:29:38 +0000)
  Optional(2017-02-08 03:30:29 +0000)
  </code></pre>
  
  <p><strong>How can I sort it by what comes sooner? (considering the whole NSDate not just the time portion)</strong></p>
  
  <p>I want it to be:</p>
  
  <pre><code>Optional(2017-02-06 03:29:18 +0000)
  Optional(2017-02-07 03:29:38 +0000)
  Optional(2017-02-08 03:29:27 +0000)
  Optional(2017-02-08 03:30:29 +0000)
  </code></pre>
  
  <p><strong>Complete Code</strong>
      All tasks completed are 0 in the list and I'm calling:</p>
  
  <pre><code>helper(showComp: true, sortBy: NSSortDescriptor.init(key: "due", ascending: false))
  </code></pre>
  
  <p>helper func:</p>
  
  <pre><code>func helper(showComp: Bool, sortBy: NSSortDescriptor?){
  let g = cur as! Group
  guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
      return
  }
  
  let managedContext = appDelegate.persistentContainer.viewContext
  
  let fetchRequest = NSFetchRequest&lt;NSManagedObject&gt;(entityName: "Task")
  let sortDescriptor0 =  NSSortDescriptor.init(key: "completed", ascending: true)
  let sortDescriptor =  NSSortDescriptor.init(key: "index", ascending: true)
  if sortBy == nil {
      fetchRequest.sortDescriptors = [sortDescriptor0, sortDescriptor]
  }else{
      fetchRequest.sortDescriptors = [sortDescriptor0, sortBy!]
  }
  if (cur as! Group).name != "All"{
      var predicate = NSPredicate(format: "group = %@", argumentArray: [g])
      if !showComp {
          predicate = NSPredicate(format: "group = %@ &amp;&amp; completed = %@", argumentArray: [g, 0])
      }
      fetchRequest.predicate = predicate
  }
  do {
      groups = try managedContext.fetch(fetchRequest)
  } catch let error as NSError {
      print("Could not fetch. \(error), \(error.userInfo)")
  }
  </code></pre>
  
  <p><strong>Photo of the core data attribute</strong>
  <a href="https://i.stack.imgur.com/AlwHd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AlwHd.png" alt="enter image description here"></a></p>