菜鸟教程——iOS时间处理

1.时间字符串的转化

//日期转时间

- (NSString*)dateToString:(NSDate*)date {

NSDateFormatter* dateFormatter = [[NSDateFormatteralloc] init];  

   [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString*dateString = [dateFormatter stringFromDate:date];returndateString;}

//字符串转时间戳

- (NSTimeInterval)dateWithString:(NSString*)string {

NSDateFormatter*dateFormatter = [[NSDateFormatteralloc] init];   

 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

NSDate*date = [dateFormatter dateFromString:string];returndate.timeIntervalSince1970;

}

2.常见的时间转化

- (NSString *)formattedDateDescription{   

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    [dateFormattersetDateFormat:@"yyyy-MM-dd"];   

 NSString *theDay = [dateFormatterstringFromDate:self];

//日期的年月日

NSString *currentDay = [dateFormatterstringFromDate:[NSDate date]];

//当前年月日

NSInteger timeInterval = -[self timeIntervalSinceNow];

if(timeInterval <60) {return@"1分钟内";    }

elseif(timeInterval <3600)

 {//1小时内

return[NSStringstringWithFormat:@"%ld分钟前", timeInterval /60];    }

elseif(timeInterval <21600) {//6小时内

return[NSStringstringWithFormat:@"%ld小时前", timeInterval /3600];    }

elseif([theDayisEqualToString:currentDay]) {//当天

[dateFormattersetDateFormat:@"HH:mm"];

return[NSStringstringWithFormat:@"今天 %@", [dateFormatterstringFromDate:self]];    }

elseif([[dateFormatterdateFromString:currentDay]timeIntervalSinceDate:[dateFormatterdateFromString:theDay]] ==86400) {//昨天

[dateFormattersetDateFormat:@"HH:mm"];

return[NSStringstringWithFormat:@"昨天 %@", [dateFormatterstringFromDate:self]];    }

else{//以前

[dateFormattersetDateFormat:@"MM-dd HH:mm"];

return[dateFormatterstringFromDate:self];    }}

3.已经知道当前时间,计算未来或者以前的时间

NSCalendar*calendar = [NSCalendarcurrentCalendar];   

 calendar.timeZone = [NSTimeZonelocalTimeZone];

NSDateComponents*comp = [calendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:date];//comp可以修改年月日等时间

[comp setDay:1];NSDate*firstDayOfMonthDate = [calendar dateFromComponents:comp];

4.固定app的时区,不会根据位置改变(下面是东八区)

[NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+0800"]];

你可能感兴趣的:(菜鸟教程——iOS时间处理)