Friday, May 10, 2013

NSDateFormatter localizedStringFromDate example ios


localizedStringFromDate :dateStyle:timeStyle:

Returns string representation of a given date formatted for the current locale using the specified date and time styles.
+ (NSString *)localizedStringFromDate:(NSDate *)date dateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle
Parameters of [NSDateFormatter localizedStringFromDate]
date
A date.
dateStyle
A format style for the date. For possible values, see NSDateFormatterStyle.
timeStyle
A format style for the time. For possible values, see NSDateFormatterStyle.
Return Value
A localized string representation of date using the specified date and time styles
Discussion of [NSDateFormatter localizedStringFromDate]
This method uses a date formatter configured with the current default settings. The returned string is the same as if you configured and used a date formatter as shown in the following example:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[formatter setDateStyle:dateStyle];
[formatter setTimeStyle:timeStyle];
NSString *result = [formatter stringForObjectValue:date];

Example of [NSDateFormatter localizedStringFromDate]
self.creationDate.text = [NSDateFormatter localizedStringFromDate:creationTimeStamp
                                          dateStyle:NSDateFormatterMediumStyle
                                          timeStyle:NSDateFormatterShortStyle];
Example of [NSDateFormatter localizedStringFromDate]
NSDate* date = [NSDate date];
NSString* datePart = [NSDateFormatter localizedStringFromDate: date 
                                                    dateStyle: NSDateFormatterShortStyle 
                                                    timeStyle: NSDateFormatterNoStyle];
NSString* timePart = [NSDateFormatter localizedStringFromDate: date 
                                                    dateStyle: NSDateFormatterNoStyle 
                                                    timeStyle: NSDateFormatterShortStyle];
NSLog(@"Month Day: %@", datePart);
NSLog(@"Hours Min: %@", timePart);
Example of [NSDateFormatter localizedStringFromDate]
//If this is not in UTC, we don't have any knowledge about
//which tz it is. MUST BE IN UTC.
dateString = "2012-03-12 9:53:23"

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM dd yyyy hh:mma"];

NSDate *date = [formatter dateFromString:dateString];

NSString *result = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle];

//The result should be in MY timezone automatically.