iPhone开发--NSData年、月、星期、日、时、分、秒和毫秒获取及NSDataToNSString方法

来源:互联网 发布:c语言各种符号含义 编辑:程序博客网 时间:2024/05/19 02:30

在 NSDate中获得时间信息,年、月、星期、日、时、分、秒和毫秒:

注:第一种方法不能获取毫秒的信息,最后利用第二种方法实现了获取毫秒的信息

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方法: 
-(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]; 
//  [fmt setDateFormat:@"hh:mm:ss:SSS"]; 
  [fmt setDateFormat:@"yyyy/MM/dd hh:mm:ss:SSS"];   NSString *string=[fmt stringFromDate:nsDate];   return string; }

本文转载自:http://hobo86.iteye.com/blog/1013030