-1

I have string "2013-12-23T12:02:01+05:30" i want to convert into date but i am getting NSDate nil here is my code

        // Convert string to date object
        NSString *dateStr = @"2013-12-23T12:02:01+05:30";
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy, MM DD 'T' HH:mm:ss Z"];
        NSDate *date = [dateFormat dateFromString:dateStr];
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
Bevan
  • 342
  • 2
  • 14
  • possible duplicate of [How to parse a date string into an NSDate object in iOS?](http://stackoverflow.com/questions/4999396/how-to-parse-a-date-string-into-an-nsdate-object-in-ios) – Matthias Bauch Jan 03 '14 at 08:09
  • 1
    the formatter `@"yyyy, MM DD 'T' HH:mm:ss Z"` is incorrect in so many ways for string `@"2013-12-23T12:02:01+05:30"`... probably that causes a `nil` value. – holex Jan 03 '14 at 09:30
  • thnx @MatthiasBauch, i got it – Bevan Sep 30 '15 at 14:19

2 Answers2

2

Your string format does not match you date string:

    NSString *dateStr = @"2013-12-23T12:02:01+05:30";
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSDate *date = [dateFormat dateFromString:dateStr];

In you example date sting there are - used in the date, in the format you are using uses . Also DD will give you the day in the year not in the month. and there is no space after the seconds and time zone offset.

rckoenes
  • 69,092
  • 8
  • 134
  • 166
  • Date will always be present with the GMT time zone. When you present a date to the user use `NSDateFormatter` and set the correct time zone. – rckoenes Jan 03 '14 at 08:53
  • how to set time zone of incomeing string? – Bevan Jan 03 '14 at 08:54
  • i am using [dateFormat setTimeZone:[NSTimeZone systemTimeZone]]; after allocation of date formatter – Bevan Jan 03 '14 at 08:55
  • When parsing a date without a time zone the time zone set is used. But in your example the date has a time zone. `NSDateFormatter` will parse this time zone. – rckoenes Jan 03 '14 at 08:59
0

You need to set the correct date format to match with the date string

NSString *dateStr = @"2013-12-23T12:02:01+05:30";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [dateFormat dateFromString:dateStr];
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60
  • The `DD` in your time stamp will not work, since `DD` will should give you the day of the year not month. – rckoenes Jan 03 '14 at 08:58