0

I having a date string:

Wed Mar 25 2017 05:30:00 GMT+0530 (IST)

I want to convert this string to the Date object in Swift 3.

I have referred to Link1, Link 2 and Link 3 for generating the format for this date string but could not get the correct format.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Foramkumar Parekh
  • 421
  • 1
  • 6
  • 26
  • As I said, the concern is not with the code, the concern is I am unable to get the format for the mentioned date string. – Foramkumar Parekh May 29 '17 at 06:26
  • 2
    This one is interesting. The format `"EEE MMM dd yyyy HH:mm:ss 'GMT'Z (z)"` should work. That format will format a `Date` object into the same format shown in the question and it will properly parse a string in the format shown in the question but only if it is some other timezone. `DateFormatter` doesn't seem to like the `IST` timezone. I had no trouble parsing the string `"Wed Mar 25 2017 05:30:00 GMT-0500 (CDT)"` using the format I mentioned. – rmaddy May 29 '17 at 06:27
  • 1
    There are definitely issues with the `IST` timezone. Please see [these search results](https://stackoverflow.com/search?q=dateformatter+ist). Since it's ambiguous, `DateFormatter` can't handle it when parsing. – rmaddy May 29 '17 at 06:41
  • 2
    `IST` is ambiguous as it stands for both `Irish Standard Time` and `Indian Standard Time` – roy May 29 '17 at 06:58

2 Answers2

0

1) If you have string which contains timezone names like IST or GMT differences, then you can use NSDateDetector as explained in this SO post answer:

extension String {
  var nsString: NSString { return self as NSString }
  var length: Int { return nsString.length }
  var nsRange: NSRange { return NSRange(location: 0, length: length) }
  var detectDates: [Date]? {
    return try? NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
        .matches(in: self, range: nsRange)
        .flatMap{$0.date}
  }
}

//your example here
let dateString = "Wed Mar 25 2017 05:30:00 GMT+0530 (IST)"
if let dateDetected = dateString.detectDates?.first {
    let date = dateDetected//Mar 25, 2017, 5:30 AM
    print(dateDetected)//2017-03-25 00:00:00 +0000 - this is GMT time
}

Mar 25, 2017, 5:30 AM //date converted to local time zone
2017-03-25 00:00:00 +0000 //printed value of GMT time


2) Or if you some how able to remove GMT and IST reference from your string then try this:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, MMM d yyyy HH:mm:ss Z"
let date = dateFormatter.date(from: "Wed Mar 25 2017 05:30:00 +0530")!
print(date)

It will give you

Mar 25, 2017, 5:30 AM //date converted to local time zone
2017-03-25 00:00:00 +0000 //printed value of GMT time

D4ttatraya
  • 3,344
  • 1
  • 28
  • 50
-1
var dateString = "Wed, 25 Mar 2017 05:30:00 +0000"
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
var dateFromString = dateFormatter.date(from: dateString)
print(dateFromString)