27

I am geting below date from the server now I want to convert string to date.

Wed, 08 Jun 2011 11:58 pm EDT

But I cant success please give me advice. Thanks

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
ManthanDalal
  • 1,063
  • 2
  • 20
  • 45

2 Answers2

89

How-To: Convert a string to NSDate

In Objective-C, you commonly nead to convert a string to an NSDate object. A simple way to do this is using the NSDateFormatter object. It provides the dateFromString method which converts a string into an NSDate object. You do, however, need to tell NSDateFormatter the format the date will be in. See below example:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];
NSDate *myDate = [df dateFromString: myDateAsAStringValue];

And read about EDT – Eastern Daylight Time I think it would be better you change EDT to -0004.

Community
  • 1
  • 1
Viktor Apoyan
  • 10,655
  • 22
  • 85
  • 147
  • 1
    Note, you should use _HH_ instead of _hh_, like this `[df setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];`, otherwise in 24-hour format `dateFromString:` sometimes returns `nil` – Lion Jul 10 '13 at 09:37
  • 4
    ProTip: If you're parsing lots of data, be sure to recycle your date formatter as they're expensive to create every time. – oliland Dec 30 '13 at 21:53
  • This gives me nill?? any idea why? – IamDev Jun 05 '17 at 09:03
17

ViTo basically answers this, but the precise format you're looking at for the string you are concerned with is:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM y hh:mm a zzz"];
NSLog(@"Date: %@", [dateFormatter dateFromString:@"Wed, 08 Jun 2011 11:58 pm EDT"]);

Take a look at the date format patterns. I add this because it wasn't immediately obvious where to find a description of the pattern.

Ben Flynn
  • 18,524
  • 20
  • 97
  • 142