NSDateFormatter用法

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

[dateFormatter setAMSymbol:@"AM"];

[dateFormatter setPMSymbol:@"PM"];

[dateFormatter setDateFormat:@"yyyy年MM月dd日 hh:mmaaa"];

NSDate *date = [NSDate date];

NSString * s = [dateFormatter stringFromDate:date];

显示效果为:2012年09月01日 03:49PM



下面附上几个格式:这个是从Cocoachina上来的

yyyy:MM:dd G 'at' HH:mm:ss zzz            1996.07.10 AD at 15:08:56 PDT

EEE, MMM d, "yy                                         Wed,july 10, '99

h:mm a                                                     12:08 PM

hh 'o"clock' a,zzzz                                      12 o'clock PM, Pacific Daylight Time

K:mm a, z                                                 0:00 PM, PST

yyyyy,MMMM.dd GGG hh:mm aaa                01996.july.10 AD 12:08 PM



下面是得到当前的年,月,日,时,分,秒。

NSCalendar *cal = [NSCalendar currentCalendar];

unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *dd = [cal components:unitFlags fromDate:date]; 

int y = [dd year];

int m = [dd month];

int d = [dd day];

int h = [dd hour];

int m = [dd minute];

int s = [dd second];


iOS计时器

 NSDate *date1 = [NSDate date];
    sleep(2);
    NSDate *date2 = [NSDate date];
    //怎样将date2与date1的时间间隔表示为:00:00:10 的形式
   NSTimeInterval time = [date2 timeIntervalSinceDate:date1];
    NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:time];
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"HH:mm:ss"];
    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [df setTimeZone:gmt];
    NSString *str = [df stringFromDate:date];
    NSLog(@"%@",str);
    //结果:08:00:10



你可能感兴趣的:(NSDateFormatter用法)