13

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.

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)

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

I always get a nil value

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
WDFAN23
  • 159
  • 1
  • 2
  • 6
  • The question should be more generic, like "Convert string to data", you also do not need to add tags in your question, as they are displayed further down. Finally you should also so in what context and what you've tried so far. – Emz Jul 27 '15 at 19:19
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. – Hot Licks Jul 27 '15 at 19:36
  • possible duplicate of [SWIFT: How to convert string date to NSDate](http://stackoverflow.com/questions/24777496/swift-how-to-convert-string-date-to-nsdate) – Lucas Huang Jul 29 '15 at 21:21

4 Answers4

42

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

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
Andres Kievsky
  • 3,461
  • 32
  • 25
MirekE
  • 11,515
  • 5
  • 35
  • 28
0

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

Good Doug
  • 2,072
  • 15
  • 12
0

In 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) 
Muthama Kahohi
  • 119
  • 2
  • 6
0

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

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

shiva
  • 41
  • 3