1016-09-首頁22-日期轉換,1016-09-首頁22-

來源:互聯網
上載者:User

1016-09-首頁22-日期轉換,1016-09-首頁22-

兩個NSDate之間是可以進行比較的。

有了NSCalendar比較兩個日期就易如反掌

 


/**
 1.今年
 1> 今天
 * 1分內: 剛剛
 * 1分~59分內:xx分鐘前
 * 大於60分鐘:xx小時前
 
 2> 昨天
 * 昨天 xx:xx
 
 3> 其他
 * xx-xx xx:xx
 
 2.非今年
 1> xxxx-xx-xx xx:xx
 */
- (NSString *)created_at
{
    // _created_at == Thu Oct 16 17:06:25 +0800 2014
    // dateFormat == EEE MMM dd HH:mm:ss Z yyyy
    // NSString --> NSDate
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    // 如果是真機調試,轉換這種歐美時間,需要設定locale
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    
    // 設定日期格式(聲明字串裡面每個數字和單詞的含義)
    
    // E:星期幾
    // M:月份
    // d:幾號(這個月的第幾天)
    // H:24小時制的小時
    // m:分鐘
    // s:秒
    // y:年
    fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
    
    // 微博的建立日期
    NSDate *createDate = [fmt dateFromString:_created_at];
    // 目前時間
    NSDate *now = [NSDate date];
    // 日曆對象(方便比較兩個日期之間的差距)
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // NSCalendarUnit枚舉代表想獲得哪些差值
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 計算兩個日期之間的差值
    NSDateComponents *cmps = [calendar components:unit fromDate:createDate toDate:now options:0];
    
    HWLog(@"%@ %@ %@", createDate, now, cmps);
    
    return _created_at;
}

相關文章

聯繫我們

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