Question

I would like to format a date to display in a uitableview custom cell

The data is passed into the app from a CMS - it is provided as a string in the following format and stored in a date type variable-

2014-04-15 10:10:45 +0000

Our app will initially be UK based - so I need to convert the format into DD/MM/YYYY format.

I tried the following code to parse my date (dateadded which is of type date).

NSDateFormatter *formatter = [NSDateFormatter new];
cellRecP.artDate.text = [formatter stringFromDate:resItem.dateadded];

but this just returns null - i guess the date format provided above is not anything that stringfromdate understands - is there any other way to format date?

Was it helpful?

Solution

Use an 'NSDateFormatter'

NSDateFormatter* newFormatter = [[[NSDateFormatter alloc] init] autorelease];

with this format to parse the string

[newFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];
NSDate* aDate = [newFormatter dateFromString:dateString];

and you should get a valid 'NSDate' object

OTHER TIPS

Try This and also Checkout this All Formate It is really good and helpful.

NSString *yourString = @"2014-04-15 10:10:45 +0000";
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setTimeZone:[NSTimeZone systemTimeZone]];//Set Your Timezone
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];//You have to set this formate.
NSDate *dd = [df dateFromString:yourString];//This will convert into date;
//Now you can set your formate.
[df setDateFormat:@"dd/MM/yyyy"];
NSString *str = [df stringFromDate:dd];

You need an NSDateFormatter and a proper unicode parse string. NSDateFormatter by default automatically checks the device locale setting the correct output. This is an example from some code of mine:

        NSDateFormatter *dateWriter = [[NSDateFormatter alloc] init];
        dateWriter.dateFormat = @"yyyy'-'MM'-'dd' 'HH':'mm':'ss' 'ZZZ";
        dateWriter.dateStyle = NSDateFormatterMediumStyle;
        dateWriter.timeStyle = NSDateFormatterMediumStyle;

Pay attention that date formatters are pretty expensive to create.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top