-3

I am developing an iOS app using Swift. I am accessing data from server and it is returning data in JSON format. In that I am having a field 'ExpiryDate' which is getting from that JSON and converted to string as follows:

var validityDate = offerElements[indexPath.row]["endDate"].stringValue

It is returning date of following format:

2015-08-24T00:00:00.000Z

I wanna convert it to MM/DD/YYYY, how can I do it ?

Your suggestions are most welcome. Thank you in advance.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Chetan Purohit
  • 364
  • 1
  • 3
  • 16
  • 1
    Googling `Swift convert string to nsdate` did not help? – Pekka Sep 30 '15 at 05:38
  • No. It is not working. – Chetan Purohit Sep 30 '15 at 05:39
  • @ChetanPurohit use `NSDateFormatter` class to achieve so. – Dipen Panchasara Sep 30 '15 at 05:39
  • 1
    There are about 45,000 hits for that query. One of them is extremely likely to do what you need (or give you enough information that you can figure out the rest). Stack Overflow isn't a mechanical turk. – Pekka Sep 30 '15 at 05:40
  • I have tried to use this : var validityDate = offerElements[indexPath.row]["endDate"].stringValue var currentDate = NSDate(validityDate) var dateString = dateFormatter.stringFromDate(validityDate) @Dipen, But it is throwing error : Cannot find an initializer for type 'NSDate' that accepts an argument list of type '(String)' – Chetan Purohit Sep 30 '15 at 05:44
  • @ChetanPurohit of course it will, you can't directly type cast string to date. first convert your string to date using `NSDateFormatter` then again convert that date to your desired format. i hope its clear to you. – Dipen Panchasara Sep 30 '15 at 05:46
  • @ChetanPurohit To me, it gave this result on top: http://stackoverflow.com/questions/24777496/how-can-i-convert-string-date-to-nsdate (Existing Stack Overflow question, 35 up votes as of now.). Google _**is**_ your friend. – Nicolas Miari Sep 30 '15 at 05:53

1 Answers1

1

This should work with minimal or no changes

    func dateFromString(dateString: String) -> NSDate {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

        return dateFormatter.dateFromString(dateString)!
    }
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Sahil Kapoor
  • 11,183
  • 13
  • 64
  • 87