【问题标题】:Getting date from parse and displaying to a string Swift从解析中获取日期并显示为字符串 Swift
【发布时间】:2015-12-10 05:33:26
【问题描述】:

就像标题说的那样,我正在从解析中获取信息并显示它,但我无法弄清楚如何使用日期来执行此操作。我需要将它覆盖到一个字符串以显示在标签中。我做了一些或研究并了解我将需要使用日期格式化程序,但我不明白的是我把它放在哪里以及一旦格式化我如何显示它。任何帮助将非常感激!

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]
        }
    }
}
}

【问题讨论】:

    标签: ios swift parse-platform nsdate


    【解决方案1】:

    您可以轻松地从 NSDate 获取字符串并显示它。

    func getStringFromDate(date:NSDate)->String{
    
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM/dd/yy, H:mm"
    return dateFormatter.stringFromDate(yourDate) // yourDate is your parse date
    }
    

    您也可以创建一个类别。

    【讨论】:

    • 好的,我会把这个放在哪里?
    • yourDate 将是您的解析日期,您必须将文本分配到标签的位置,因为此函数将为您提供来自 Date 的字符串
    • 所以我会把它放进去,对象中的对象?抱歉,一旦我有了字符串,我真的不明白如何分配它
    • 首先,您必须将代码中的这一行 self.dates.append(object["date"] as!String) 更改为 self.dates.append(object["date"] as ! 日期),然后在 cellforRowatIndexPath 中您可以将其更改为 LECell.postDate.text = self。 getStringFromDate(日期[indexPath.row])。将其分配给您的单元格标签
    • 太棒了,我从这里得到它!谢谢!
    【解决方案2】:

    斯威夫特 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
    

    【讨论】:

    • 请考虑添加一些解释。原始代码答案通常不是很有帮助。
    • 为什么?什么问题?
    • 正如我所说的 - “原始代码答案一般而言不是很有帮助”。如果您解释了您的代码,您可以让您的答案对更多人有所帮助。例如,初学者将不胜感激。此外,解释您的答案为什么以及如何解决问题中的问题只是一个好习惯。
    猜你喜欢
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    相关资源
    最近更新 更多