如何将解析日期对象转换为字符串? [英] How to convert a parse date object to a string?

查看:196
本文介绍了如何将解析日期对象转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初学者警报

我正在尝试从PFUser查询日期,然后将其格式化为NSDate,因此它更有用。当我尝试将对象转换为NSString时,麻烦就开始了,所以我可以用NSDateFormatter()格式化它。

I'm trying to query for a date from PFUser and then format it to NSDate so it is more useful. The trouble begins when I try to convert the object to a NSString so I can format it with NSDateFormatter()

    var user = PFUser.query()
    user.whereKey("username", equalTo: PFUser.currentUser().username)
    user.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if error == nil {
            for object in objects {
                var lastActive = object["lastActive"]
                if lastActive != nil {   
                let newLastActive = lastActive as String //problem starts here!!
                let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"
                let date = dateFormatter.dateFromString(newLastActive)
                println("new date \(date)")
                }

            }
        }
    }

这样做的正确方法是什么?另外,如果我没有将变量类型指定为AnyObject,它将作为可选项继续出现。如何在将其转换为String时删除可选项?

What is the correct way of doing this? Also, if I don't specify the variable type as AnyObject, it keeps coming out as a optional. How do I get rid of the optional while converting it to String?

编辑:对象lastActive是由解析云设置的日期,而不是字符串。

edit: the object "lastActive" is a date set by parse cloud, not a string.

推荐答案

如果你的lastActive单元格返回了你可以使用的日期:

If your lastActive cell returns a date you could use:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"
let date = dateFormatter.stringFromDate(lastActive as NSDate)

你不必投你的date为string,您将通过dateformatter创建日期字符串。
但是如果你这样做,你可以使用 lastActive作为! String insted of lastActive as String

You dont have to cast your date to string, you will create a date string via the dateformatter. But if you do so, you could use lastActive as! String insted of lastActive as String

UPDATED

for object in objects {
            var lastActive = object["lastActive"]
            if lastActive != nil {
                let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"
                let date = dateFormatter.stringFromDate(lastActive as NSDate)
                println(date)
            }
        }

我尝试使用上面的代码,如果您已将列设置为解析日期,则应该可以正常工作。

I tried with this code above and if you've set your column in parse to date, it should work.

这篇关于如何将解析日期对象转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆