0

So like the title says I am getting information from parse and displaying it but i can't figure out how to do this with a date. I need to cover it to a String to display in a label. Ive done a bit or research and understand I will need to use a date formatter but What I don't understand is where I put it and once its formatted how i display it. Any help would be much appreciated!

var names = [String]()
var locations = [String]()
var dates = [NSDate]()
var imageFiles = [PFFile]()
var abouts = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    refresher = UIRefreshControl()
    refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
    self.tableView.addSubview(refresher)
    refresh()

    PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint, error) -> Void in
        if let geoPoint = geoPoint {
            PFUser.currentUser()?["location"] = geoPoint
            PFUser.currentUser()?.saveInBackground()

    var getLocalPostsQuery = PFQuery(className: "publicPosts")
    if let latitude = PFUser.currentUser()!["location"].latitude {
        if let longitude = PFUser.currentUser()!["location"].longitude {
    getLocalPostsQuery.whereKey("searchLocation", withinGeoBoxFromSouthwest: PFGeoPoint(latitude: latitude - 0.5, longitude: longitude - 0.5), toNortheast:  PFGeoPoint(latitude: latitude + 0.5, longitude: longitude + 0.5))
    getLocalPostsQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if let objects = objects {

                self.names.removeAll(keepCapacity: true)
                self.locations.removeAll(keepCapacity: true)
                self.abouts.removeAll(keepCapacity: true)
                self.dates.removeAll(keepCapacity: true)
                self.imageFiles.removeAll(keepCapacity: true)

                for object in objects {

                    self.names.append(object["name"] as! String)
                    self.locations.append(object["location"] as! String)
                    self.dates.append(object["date"] as! String)
                    self.abouts.append(object["about"] as! String)
                    self.imageFiles.append(object["imageFile"] as! PFFile)
                    //self.attendings.append(object["attending"].count)
                    self.tableView.reloadData()
                            }
                        }
                    }
                }
            }
        }
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return names.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let LECell = tableView.dequeueReusableCellWithIdentifier("LocalPostsCell", forIndexPath: indexPath) as! LocalPostsTableViewCell

    imageFiles[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in
        if let downloadedImage = UIImage(data: data!) {

            LECell.postImage.image = downloadedImage
        }
    }


    LECell.postName.text = names[indexPath.row]
    LECell.postLocation.text = locations[indexPath.row]
    LECell.postDate.text = dates[indexPath.row]

    return LECell
}

let localPostsDetailSegue = "showLocalPostsDetailView"

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == localPostsDetailSegue {
        let detailScene = segue.destinationViewController as! LocalPostsDetailViewController

        if let indexPath = self.tableView.indexPathForSelectedRow {
            let row = Int(indexPath.row)
            detailScene.name = names[row]
            detailScene.location = locations[row]
            detailScene.date = dates[row]
            detailScene.about = abouts[row]
            detailScene.photo = imageFiles[row]
        }
    }
}
}

2 Answers 2

1

You can easily get string from NSDate and show it.

func getStringFromDate(date:NSDate)->String{

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yy, H:mm"
return dateFormatter.stringFromDate(yourDate) // yourDate is your parse date
}

you can make a category too.

Sign up to request clarification or add additional context in comments.

5 Comments

Ok so where would I put this?
yourDate will be your parse date and you have to put where you want to assign text to your label because this func will give you String from Date
So I would put it in, for object in objects? Sorry I just really don't understand how to assign it once I have the string
First of all you have to change this line in your code self.dates.append(object["date"] as! String) to self.dates.append(object["date"] as! Date) and then in cellforRowatIndexPath you can change it to LECell.postDate.text = self. getStringFromDate(dates[indexPath.row]). will assign it to your cell label
Awesome I got it from here! Thanks!
0

Swift 3:

 func getFormattedDate(string: String) -> String{


 let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz" // 2017-04-20T09:40:30+0000
        let formateDate = dateFormatter.date(from: string)!
        dateFormatter.dateFormat = "dd-MM-yyyy"
        return dateFormatter.string(from: formateDate)
        }
    let CreatedDates = "\(Date.getFormattedDate(string: "\(records["creationDate"]!)"))"
print("Date : \(CreatedDates)")
        //OutPut 
         20-04-2017

3 Comments

Please consider adding some explanations. Raw code answers are not very helpful in general.
why ? what problem?
As I've said - "raw code answers are not very helpful in general". You could make your answer helpful to more people if you've explained your code. Beginners, for example, will be grateful. Also, it's just a good practice to explain why and how does your answer address the problem from the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.