在 NSDate中獲得時間信息,年、月、星期、日、時、分、秒和毫秒:
注:第一種方法不能獲取毫秒的信息,最後利用第二種方法實現了獲取毫秒的信息
[cpp] NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now;
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
now=[NSDate date];
comps = [calendar components:unitFlags fromDate:now];
int year=[comps year];
int week = [comps weekday];
int month = [comps month];
int day = [comps day];
int hour = [comps hour];
int min = [comps minute];
int sec = [comps second];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now;
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
now=[NSDate date];
comps = [calendar components:unitFlags fromDate:now];
int year=[comps year];
int week = [comps weekday];
int month = [comps month];
int day = [comps day];
int hour = [comps hour];
int min = [comps minute];
int sec = [comps second]; NSDataToNSString方法:
[cpp] -(NSString *)NSDateToNSTring:(NSDate *)nsDate{
//NSString *string = [nsDate descriptionWithCalendarFormat:@"%Y/%m/%d %H:%M:%S" timeZone:nil locale:nil];此方法為是有API如果要上傳APP不要使用
NSDateFormatter *fmt = [[[NSDateFormatter alloc] init] autorelease];
-(NSString *)NSDateToNSTring:(NSDate *)nsDate{
//NSString *string = [nsDate descriptionWithCalendarFormat:@"%Y/%m/%d %H:%M:%S" timeZone:nil locale:nil];此方法為是有API如果要上傳APP不要使用
NSDateFormatter *fmt = [[[NSDateFormatter alloc] init] autorelease]; [cpp] // [fmt setDateFormat:@"hh:mm:ss:SSS"];
// [fmt setDateFormat:@"hh:mm:ss:SSS"]; [cpp] [fmt setDateFormat:@"yyyy/MM/dd hh:mm:ss:SSS"];
NSString *string=[fmt stringFromDate:nsDate];
return string;
[fmt setDateFormat:@"yyyy/MM/dd hh:mm:ss:SSS"];
NSString *string=[fmt stringFromDate:nsDate];
return string;
}
摘自 zcl369369的專欄