tags:

views:

340

answers:

2
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *formatterDate = [inputFormatter dateFromString:@"2009-11-03T21:02:34-08:00"];
[inputFormatter release];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"HH:mm 'on' yyyy/MM/dd"];
[outputFormatter setTimeStyle:NSDateFormatterShortStyle];
[outputFormatter setDateStyle:NSDateFormatterShortStyle];


NSString  *newDateString = [outputFormatter stringFromDate:formatterDate];
NSLog(@"newDateString %@", newDateString);

outputing the date first and time after that how to resolve this ?

I want to display time in short style and than date

+1  A: 

When you set the time and date styles, you override the date format that you set manually.

Try this:

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *formatterDate = [inputFormatter dateFromString:@"2009-11-03T21:02:34-08:00"];
[inputFormatter release];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];

//[outputFormatter setDateFormat:@"HH:mm 'on' yyyy/MM/dd"];
//[outputFormatter setTimeStyle:NSDateFormatterShortStyle];
//[outputFormatter setDateStyle:NSDateFormatterShortStyle];
//NSString  *newDateString = [outputFormatter stringFromDate:formatterDate];

// format for time only
[outputFormatter setTimeStyle:NSDateFormatterShortStyle];
[outputFormatter setDateStyle:NSDateFormatterNoStyle];

// get time
NSString *newTimeString = [outputFormatter stringFromDate:formatterDate];

// format for date only
[outputFormatter setTimeStyle:NSDateFormatterNoStyle];
[outputFormatter setDateStyle:NSDateFormatterShortStyle];

// get date and format with time
NSString *newDateString = [NSString stringWithFormat:@"%@ on %@", newTimeString, [outputFormatter stringFromDate:formatterDate]];

NSLog(@"newDateString %@", newDateString);
gerry3
A: 

Setting the timeStyle or dateStyle means that the formatter ignores the dateFormat you've set. If you always want your dates to be formatted as 00:00 on 2009/11/04 regardless of the locale of the user, you should set the locale like this:

NSDateFormatter*outputFormatter = [[[NSDateFormatter alloc] init] autorelease];
NSLocale* locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
[outputFormatter setLocale:locale];
[outputFormatter setDateFormat:@"HH:mm 'on' yyyy/MM/dd"];

NSString* newDateString = [outputFormatter stringFromDate:formatterDate];

Note that you should always set the locale to en_US_POSIX if you're dealing with machine-read dates (e.g. ISO 8601), since some locales will turn 'HH' into 'hh' which can have unexpected results.

Nathan de Vries