如何从swift 3中的String获取日期? [英] How to get Date from String in swift 3?

查看:151
本文介绍了如何从swift 3中的String获取日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将时间戳保存在数据库中,例如:

I have save the timestamp in data base like:

"NSDate()" // which save Date like this: 2017-03-10 22:53:30 +0000

现在我需要从这个字符串中获取日期,我已尝试过各种格式,但它会一直返回nil。

Now i need to get Date from this string, I have tried every format but it's keep returning nil.

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss ZZZ"
    dateFormatter.locale = Locale(identifier: "en_US")
    print(dateFormatter.date(from: "2017-03-10 22:53:30 +0000") ?? "No Value") // always return No Value

这里我已尝试过如此多的格式,例如:
yyyy-MM-dd hh:mm:ss + zzzz
yyyy-MM-dd hh:mm:ss xx

here i have tried so many formats e.g: yyyy-MM-dd hh:mm:ss +zzzz yyyy-MM-dd hh:mm:ss xx

已经看到很多答案,但没有答案正在处理这种格式的日期2017-03-10 22:53:30 +0000

Have seen many answers but no answer is working on this format of date "2017-03-10 22:53:30 +0000"

推荐答案

军事时间(24个值小时)使用大写字母H。试试这个格式化字符串:

Military time (24-value hours) uses the capital 'H'. Try this for your formatting String:

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"

这篇关于如何从swift 3中的String获取日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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