IOS NSString與NSDate互相轉換及NSDate比較

來源:互聯網
上載者:User

標籤:

由 NSDate 轉換為 NSString:

  1. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  2. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  3. NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
  4. NSLog(@"%@", strDate);

 

結果:

  1. 2015-06-14 13:01:03

 

 

由 NSString 轉換為 NSDate:

  1. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  2. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  3. NSDate *date = [dateFormatter dateFromString:@"2010-08-04 16:01:03"];
  4. NSLog(@"%@", date);

 

結果:

  1. 2015-06-14 13:01:03 +0800

 

日期之間比較可用以下方法

    - (BOOL)isEqualToDate:(NSDate *)otherDate;

    與otherDate比較,相同返回YES

 

    - (NSDate *)earlierDate:(NSDate *)anotherDate;

    與anotherDate比較,返回較早的那個日期

 

    - (NSDate *)laterDate:(NSDate *)anotherDate;

    與anotherDate比較,返回較晚的那個日期

 

    - (NSComparisonResult)compare:(NSDate *)other;

    該方法用於排序時調用:

      . 當執行個體儲存的日期值與anotherDate相同時返回NSOrderedSame

      . 當執行個體儲存的日期值晚於anotherDate時返回NSOrderedDescending

      . 當執行個體儲存的日期值早於anotherDate時返回NSOrderedAscending

IOS NSString與NSDate互相轉換及NSDate比較

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.