Convert NSString to Date

I have two lines: date1 = 3-3-2011;

and I want to convert it to March 3, 2011 and display it in a label.

NSString *myString = 3-3-2011; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"d-MM-YYYY"]; NSDate *yourDate = [dateFormatter dateFromString:myString]; //now format this date to whatever you need… [dateFormatter setDateFormat:@"d-MMM-YYYY"]; NSString *resultString = [dateFormatter stringFromDate:yourDate]; [dateFormatter release]; 

but yourdate = 2010-12-25 18:30:00 +0000

resultstring = 26-Dec-2010

I want March 3, 2010

Please, help! Thanks.

+7
source share
3 answers

You can use NSDateFormatter .

  • Convert the current string to an NSDate object so you can convert it to any format.

     NSString *myString = @"3-3-2011"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"dM-yyy"]; NSDate *yourDate = [dateFormatter dateFromString:myString]; 
  • Now you can convert this NSDate to any format.

     [dateFormatter setDateFormat:@"d-MMMM-yyyy"]; NSString *resultString = [dateFormatter stringFromDate:yourDate]; [dateFormatter release]; 

Apple's documentation for NSDateFormatter here .

+12
source

Take a look at NSDateFormatter . In particular, take a look at the dateFromString: and stringFromDate: methods. You will need to convert the original string to NSDate, and then convert the NSDate to another string.

One tip for using NSDateFormatter: be sure to set the locale. If you do not set the language manually, it has an error regarding the 12/24 hour clock settings. The sample code on the page I'm linked to shows how to set the locale.

+2
source

Use dMY (or MdY, depending on which month):

 NSString *myString = 3-3-2011; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"dMY"]; NSDate *yourDate = [dateFormatter dateFromString:myString]; 

And look at the Unicode standard mentioned in Apple docs.

+2
source

All Articles