Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting NSString to Date

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

and i want to convert in to 3-March-2011 and display it in 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 3-March-2010

please help! Thank you.

like image 229
Sam007 Avatar asked Apr 09 '11 11:04

Sam007


3 Answers

You can use NSDateFormatter.

  1. Convert your current string to NSDate object, so that you can convert it into any format you want.

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

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

Apple's documentation on NSDateFormatter is here.

like image 57
Krishnabhadra Avatar answered Oct 24 '22 12:10

Krishnabhadra


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

One tip for using NSDateFormatter: be sure always to set a locale. If you don't manually set a locale, it has a bug regarding 12/24 hour clock settings. The example code on the page I linked to shows how to set a locale.

like image 34
Amy Worrall Avatar answered Oct 24 '22 14:10

Amy Worrall


Use d-M-Y (or M-d-Y, depending on which is the month):

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

And see the Unicode standard referred to in the Apple docs.

like image 27
Hwee-Boon Yar Avatar answered Oct 24 '22 13:10

Hwee-Boon Yar