ios - Swift - Sorting By Date Issue -
i'm using nssortdescriptor
s sort array
date element. date set string
using formatter formats in style : "dd/mm/yy hh:mm". date element stored inside dictionaries stored in array. parts of code below:
// date formatting let currenttime = date() let timeformatter = dateformatter() timeformatter.locale = locale.current timeformatter.dateformat = "hh:mm dd/mm/yy" let convertedtime:string! = timeformatter.string(from: currenttime) // descriptor let descriptord: nssortdescriptor = nssortdescriptor(key: "date", ascending: false) // dictionary let newuserrecord = [ "name" : enteredname!, "score" : self.gamescore, "date" : convertedtime ] [string : any] // sorting newuserarray.sort(using: [descriptord])
however problem date being sorted time (hh:mm) , not taking in account (dd/mm/yy) part. example if sort date , have date of 13:12 19/11/16 , date of 09:12 18/11/16 09:12 date appear first though should 13:12 day later. how fix this?
this object oriented swift way:
declare struct rather dictionary , include time formatter
struct user { let timeformatter : dateformatter = { let formatter = dateformatter() formatter.locale = locale.current formatter.dateformat = "hh:mm dd/mm/yy" return formatter }() let name : string let score : int let time : date var convertedtime : string { return timeformatter.string(from: time) } }
declare array of user
type , add 2 instances
var newuserarray = [user]() newuserarray.append(user(name: "foo", score: 12, time: date().addingtimeinterval(1000.0))) newuserarray.append(user(name: "bar", score: 78, time: date()))
sort array time descending
newuserarray.sort(by: {$0.time > $1.time })
and print formatted date
print(newuserarray[0].convertedtime)
Comments
Post a Comment