把字符串“Thu Oct 16 17:06:25 +0800 2014”轉換成 EEE MMM dd HH:mm:ss Z yyyy格式,并且比較創(chuàng)建時的日期和現(xiàn)在時間的差值。
// _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"];
//設置日期格式(聲明字符串里面每個數(shù)字和單詞的含義)
// E:星期幾
// M:月份
// d:幾號(這個月的第幾天)
// H:24小時制的小時
// m:分鐘
// s:秒
// y:年
fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
// 創(chuàng)建時的日期
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];