ios 将可选字符串转换为日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31660946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:00:32  来源:igfitidea点击:

Convert Optional string to date

iosswiftnsdatensdateformatter

提问by WDFAN23

I have this Optional(2015-07-27 19:29:50 +0000)as a string? and I want to convert it to a date (NSDate) but I can't figure it out I've been searching a lot for solutions but I am pretty new to coding so if anyone could help I would appreciate it.

我有这个Optional(2015-07-27 19:29:50 +0000)字符串?我想将它转换为日期(NSDate),但我无法弄清楚我一直在寻找解决方案,但我对编码很陌生,所以如果有人能帮助我,我将不胜感激。

This is what I am using to convert the string to a date currently.

这是我当前用来将字符串转换为日期的方法。

note: dateString is Optional(2015-07-27 19:29:50 +0000)

注意:日期字符串是 Optional(2015-07-27 19:29:50 +0000)

dateFormatter = NSDateFormatter()
println(dateFormatter)
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)

I always get a nil value

我总是得到一个零值

回答by MirekE

If you are getting nil from NSDateFormatter, you likely specified incorrect date format. Try this:

如果您从 NSDateFormatter 得到 nil,则您可能指定了不正确的日期格式。尝试这个:

let strTime = "2015-07-27 19:29:50 +0000"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
formatter.dateFromString(strTime) // Returns "Jul 27, 2015, 12:29 PM" PST

回答by Good Doug

You will want to use a NSDateFormatterand call dateFromString:on it to get the date from the string. See Apple's NSDateFormatter documentationfor a great explanation of doing what you want.

您将需要使用 aNSDateFormatter并调用dateFromString:它以从字符串中获取日期。请参阅Apple 的 NSDateFormatter 文档以获取有关执行所需操作的详细说明。

回答by Muthama Kahohi

In swift 3.0:

在 Swift 3.0 中:

let strTime = "2015-07-27 19:29:50 +0000"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
formatter.date(from: strTime) 

回答by shiva

dateString is already date and need to convert to string. Below code is working fine

dateString 已经是日期,需要转换为字符串。下面的代码工作正常

dateFormatter = NSDateFormatter() println(dateFormatter) dateFormatter.dateFormat = "yyyy-MM-dd" let s = dateFormatter.string(from: dateString)

dateFormatter = NSDateFormatter() println(dateFormatter) dateFormatter.dateFormat = "yyyy-MM-dd" let s = dateFormatter.string(from: dateString)