你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iPhone開發--NSData年、月、星期、日、時、分、秒和毫秒獲取及NSDataToNSString方法

iPhone開發--NSData年、月、星期、日、時、分、秒和毫秒獲取及NSDataToNSString方法

編輯:IOS開發綜合

在 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的專欄

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved