iOS開發之時間設定和格式輸出

來源:互聯網
上載者:User

NSDate

NSCalendar

NSDateFormatter

 
  1.    NSDate *now=[NSDate date]; 
  2.   NSCalendar *cal=[[NSCalendar alloc] 
  3.                    initWithCalendarIdentifier:NSGregorianCalendar 
  4.                    ]; 
  5.   [cal setTimeZone:[NSTimeZone systemTimeZone]]; // 3 
  6.   NSDateComponents *dc = [cal components:(NSHourCalendarUnit|NSMinuteCalendarUnit| 
  7.                                                NSSecondCalendarUnit) fromDate:now];  // 4 
  8.   //now  2013-06-13 05:45:43 +0000 
  9.     NSLog(@"The time is%@",now); 
  10.   NSLog(@"The time is%d:%d:%d",[dc hour], [dc minute], [dc second]); // 5 
  11.   NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init]; 
  12.   [dateFormatter setAMSymbol:(@"AM")]; 
  13.   [dateFormatter setPMSymbol:@"PM"]; 
  14.  // [dateFormatter setDateFormat:@"yyyy-MM-dd"]; 
  15. [dateFormatter setDateFormat:@"dd/MM/yyyy hh:mmaaa"]; 
  16.    
  17.   NSDate *curDate=[NSDate date]; 
  18.   NSString *str=[dateFormatter stringFromDate :curDate]; 
  19.   NSLog(@"%@",str); 
  20.   NSCalendar *c=[NSCalendar currentCalendar]; 
  21.   unsigned int unitFlags=NSYearCalendarUnit|NSMonthCalendarUnit| 
  22.   NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit; 
  23.   NSDateComponents *dd=[c components:unitFlags fromDate:curDate]; 
  24.   int y=[dd year]; 
  25.   int d=[dd day]; 
  26.   NSLog(@"%d 年 %d日",y,d); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.