DateFormatter not working in ios By setting

6.6k views Asked by At

I am using date formatter in xcode 6.2 with swift.It is working fine in the ios 8.1 but when I am testing my app in ios above 8.1(I tried in 8.2 and 8.4 ) the date formatter is not working. Does any one faces similar problem. This is the type of date I am getting In string format 10-08-2015T13:59:53+0000. I need to convert it in the date with Date formatter with Format "dd-MM-yyyy'T'HH:mm:ssZZZ" and this is my method to convert string to date:-

func dateFromString(dateString:String)->NSDate
    {

        print(dateString)
        var dateFormatter = NSDateFormatter()

        //yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ
        dateFormatter.dateFormat = "dd-MM-yyyy'T'HH:mm:ssZZZ"

        var date = dateFormatter.dateFromString(dateString)
        print(date)
        return date!
    }

Sorry I am editing the Qusetion. I found why it is happening. In the setting page of iphone In date & time if 24_hour_time is On It is working fine.If it is off Then only the date formatter is giving nil date.I inserted the GMT in that.It is working fine in 8.1.3 but giving problem in 8.4

 dateFormatter.timeZone = NSTimeZone(name: "GMT")

Thanks Happy coding

2

There are 2 answers

1
chakshu On BEST ANSWER

I found the answer of this question. Sorry for the delay to post the answer. You need to enter NSLocale to the formatter as I have done in this example.

func dateFromstring(dateString:String)->NSDate {
    //print(date)
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy'T'HH:mm:ssZZZ"

    //DateFormatter To change By chakshu
    var enUSPOSIXLocale:NSLocale=NSLocale(localeIdentifier: "en_US_POSIX")
    dateFormatter.locale=enUSPOSIXLocale
    dateFormatter.timeZone = NSTimeZone(name: "GMT")
    //dateFormatter.timeZone = NSTimeZone.localTimeZone()

    var date = dateFormatter.dateFromString(dateString)
    //print(date)
    return date!
}

Hope this help. Thanks

0
AudioBubble On

Warning

  • Your function name for the formatter is the same as that of your custom function. Not saying this is your problem but something that may not have been intended.
  • You are using var instead of let in some cases, again, not gonna cause an error

Otherwise, your code returns the correct date... but in Date format, not String.

To print this in your desired format just convert the Date back to the desired String format:

func dateFromString(dateString:String)->NSDate
    {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy'T'HH:mm:ssZZZ"
        let date = dateFormatter.dateFromString(dateString)
        return date!
    }

let formatter = NSDateFormatter()
formatter.dateFormat = "dd/M/yyyy, H:mm"

print(formatter.stringFromDate(dateFromString("10-08-2015T13:59:53+0000")))

Run here to test on latest Swift... no issues