2

I have this code working but now all of a sudden, it started crashing. I could not figure it out, any help would be appreciated.

 let dateFormatter = NSDateFormatter()
 dateFormat = "EEE, MMM d, yyyy hh:mm a"
 dateFormatter.dateFormat = dateFormat                  
 let date = dateFormatter.dateFromString("Thu, Jan 5, 2017 12:28 PM")

It is returning date as nil. Why? I want it to return proper date.

This looks like a possible duplicate question, but it is with specific details.

3 Answers3

0
let dateformattor = NSDateFormatter()
dateformattor.dateFormat = "EEE, MMM d, yyyy hh:mm a"
dateformattor.timeZone = NSTimeZone.localTimeZone()
let dt = "Thu, Jan 5, 2017 12:28 PM"

let dt1 = dateformattor.dateFromString(dt as String)
print(dt1) //print date and time UTC format.

Output :

2017-01-05 06:58:00 +0000 
Himanshu Moradiya
  • 4,769
  • 4
  • 25
  • 49
0
var dateFormatter = DateFormatter()
        let dateFormat = "EEE, MMM d, yyyy hh:mm a"
        dateFormatter.dateFormat = dateFormat
        let date = dateFormatter.date(from: "Thu, Jan 5, 2017 12:28 PM")

OUTPUT :

enter image description here

dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
0

Every time you work with time and date formatters remember to set locale and timezone!

Device with non-english locale will fail to parse "Thu, Jan 5, 2017 12:28 PM" as "Thu" and "Jan" are obviously english specific.

So:

dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.locale = Locale(identifier: "en_US_POSIX")

or whatever time zone and locale you want to use

Alexey Kozhevnikov
  • 4,249
  • 1
  • 21
  • 29