-1

i want to convert the string into nsdate format.

here is my string NSString str=@"Sunday, June 6, 2010 5:00:00 AM CDT";

my code is

        NSDateFormatter * Dateformats= [[NSDateFormatter alloc] init];

        [Dateformats setDateFormat:@"MM/DD/yyyy hh:mm:ss"]; //ex @"MM/DD/yyyy hh:mm:ss" 
        NSDate *myDate=[Dateformats dateFromString:str];
        NSLog(@"%@",myDate);

but it is displays null so show me the way to display the date in MM/DD/yyyy hh:mm:ss

please friends help me ,how to do this

user1402718
  • 45
  • 1
  • 1
  • 5
  • What is `k`? It's undeclared in the code snippet. Also, the declaration of DateFormats needs to be moved down or over to get into the code block. – gaige May 26 '12 at 12:20
  • You read the spec on NSDateFormatter and construct a format string to match your input. But also note you should set the locale of the date formatter to "en_US_POSIX". – Hot Licks May 26 '12 at 12:20
  • (And, as gaige points out, use the same variable name to both set and access the DateFormatter.) – Hot Licks May 26 '12 at 12:22
  • (And, standard C++/Objective-C convention is to use names with leading lower-case for variables, leading upper-case for classes.) – Hot Licks May 26 '12 at 12:24
  • Please Don't Ask Question which ask Before ... Please [Open this.][1] [1]: http://stackoverflow.com/questions/3917250/converting-nsstring-to-nsdate-and-back-again – Ashvin May 26 '12 at 13:13
  • possible duplicate of [Converting a string to an NSDate](http://stackoverflow.com/questions/2311421/converting-a-string-to-an-nsdate) – Shekhar Gupta Jul 24 '13 at 07:02

2 Answers2

6

You set your formatter to expecting a string like @"05/26/2012 8:34:00". But you give it @"Sunday, June 6, 2010 5:00:00 AM CDT". The two formats are nothing alike. It doesn't know how to parse it and so returns nil.

The format you want for the example string you give is EEEE, MMMM d, yyyy h:mm:ss a zzz.

Details here and here.

Community
  • 1
  • 1
jemmons
  • 18,605
  • 8
  • 55
  • 84
1

As you have mentioned your date string: NSString str=@"Sunday, June 6, 2010 5:00:00 AM CDT";

The date format should be like,

[dateFormatter setDateFormat:@"EEE, MMM dd, yyyy hh:mm:ss a z"];

For more details please go through this one: DateFormatter Details

Try this out, hope it will work for you..

Enjoy coding :)

Community
  • 1
  • 1
Mrunal
  • 13,982
  • 6
  • 52
  • 96