-1

I have an NSString @"2015-05-24T20:10:00.000Z", and I am using an NSDateFormatter with the date format @"yyyy-MM-dd'T'HH:mm:ssZ", but it always returns nil.

I am using the following code, but the output is always (null).

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// NSString *input = @"2013-05-08T19:03:53+00:00";
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; //iso 8601 format
NSDate *date = [dateFormat dateFromString:[dictScheduleData valueForKey:@"scheduledOn"]]; // coming from the server 2015-05-24T20:10:00.000Z
NSLog(@"Date output: %@", date);
rdurand
  • 7,342
  • 3
  • 39
  • 72
Pandey_Laxman
  • 3,889
  • 2
  • 21
  • 39
  • 1
    How the date format you used match the `NSString` format you got? – Larme May 25 '15 at 08:15
  • Are you trying to get an NSDate object from an NSString? You might want to mention that you're using NSDateFormatter too (I assume your using NSDateFormatter). If you're using NSDateFormatter, I posted an answer below. – chrisamanse May 25 '15 at 08:21
  • @Christophr I am having NSString @"2015-05-24T20:10:00.000Z from server I need to display it in the UILabel this format (5/24, 8:00PM) – Pandey_Laxman May 25 '15 at 08:25
  • Your question have been answered already http://stackoverflow.com/questions/5185230/converting-an-iso-8601-timestamp-into-an-nsdate-how-does-one-deal-with-the-utc – chrisamanse May 25 '15 at 08:27
  • For the second part, to convert it to (5/24, 8:00PM), you can change NSDateFormatter's dateFormat to "M/d, h:mma", then use NSDateFormatter's method stringFromDate. Then put that string in UILabel's text – chrisamanse May 25 '15 at 08:29
  • But after setting dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ then dateFromString is always nil So later i can again setDateFormatter to "M/d, h:mma" to get desired output – Pandey_Laxman May 25 '15 at 08:54

3 Answers3

2

Try this dateFormat

@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
Leo
  • 24,596
  • 11
  • 71
  • 92
0

You have to match the string's date format. Use NSDateFormatter, then set the date format to match the string's date format. Then use dateFromString method.

to convert it to (5/24, 8:00PM), you can change NSDateFormatter's dateFormat to "M/d, h:mma", then use NSDateFormatter's method stringFromDate (the date you previously got, which should not be nil if done correctly). Then put that string in UILabel's text.

chrisamanse
  • 4,289
  • 1
  • 25
  • 32
0
NSDate *currentTime = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[timeFormatter setLocale:[NSLocale currentLocale]];

NSString *DateString = [timeFormatter stringFromDate:currentTime];
Ghanshyam Tomar
  • 762
  • 1
  • 8
  • 24