NSDateFormatter类的实例可以将字符串的日期表示转换为NSDate对象或者反向转换。 如果只要显示日期不需要时间,则可以用-setDateStyle方法来设置显示日期的格式,有以下几种:
typedef enum { NSDateFormatterNoStyle = kCFDateFormatterNoStyle, NSDateFormatterShortStyle = kCFDateFormatterShortStyle, NSDateFormatterMediumStyle = kCFDateFormatterMediumStyle, NSDateFormatterLongStyle = kCFDateFormatterLongStyle, NSDateFormatterFullStyle = kCFDateFormatterFullStyle } NSDateFormatterStyle;
如果还要显示时间,则可以使用-setDateFormatter来设置自定义的显示格式:
更详细的内容可以到看日期格式的UNICODE标准: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
下面以一个简短的示例结束:
#import //#import int main(void){ @autoreleasepool{ NSDate *date = [NSDate date]; NSDateFormatter *f = [NSDateFormatter new]; NSString *ft = @"Y-MM-dd HH-m-SS z"; [f setDateFormat:ft]; //[f setDateStyle:NSDateFormatterFullStyle]; NSLog(@"%@",[f stringFromDate:date]); } return 0; }