NSDate formatter snippets

Posted by Daniel Vela on July 28, 2011 · 1 min read

Get a string from date object

NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
[fmt setTimeStyle:NSDateFormatterNoStyle];
[fmt setDateStyle:NSDateFormatterLongStyle];

NSLog(@“Thanksgiving is: %@”, [fmt stringFromDate:thanksgiving]);

Get a date object from a string

NSDateFormatter* fmt = [[NSDateFormatter alloc]init];
[fmt setDateFormat:@“dd/MM/yyyy HH:mm];
[fmt setTimeZone: [NSTimeZone timeZoneWithName:@“Europe/Madrid]]; // Use [NSTimeZone knownTimeZoneNames]; for other timezones [fmt setCalendar:cal];

NSDate* date = [fmt dateFromString:@“10/06/2010 9:30];

For localization use dateFormatFromTemplate

NSLocale *locale = [NSLocale currentLocale];

NSString *dateFormat;
NSString *dateComponents = @“yMMMMd;

dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:locale];
NSLog(@“Date format for %@: %@”,
[locale displayNameForKey:NSLocaleIdentifier value:[locale localeIdentifier]], dateFormat);

apple watches

20110404.20