1.時(shí)間字符串的轉(zhuǎn)化
//日期轉(zhuǎn)時(shí)間
- (NSString*)dateToString:(NSDate*)date {
NSDateFormatter* dateFormatter = [[NSDateFormatteralloc] init];??
? ?[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString*dateString = [dateFormatter stringFromDate:date];returndateString;}
//字符串轉(zhuǎn)時(shí)間戳
- (NSTimeInterval)dateWithString:(NSString*)string {
NSDateFormatter*dateFormatter = [[NSDateFormatteralloc] init];? ?
?[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate*date = [dateFormatter dateFromString:string];returndate.timeIntervalSince1970;
}
2.常見的時(shí)間轉(zhuǎn)化
- (NSString *)formattedDateDescription{? ?
?NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];? ? [dateFormattersetDateFormat:@"yyyy-MM-dd"];? ?
?NSString *theDay = [dateFormatterstringFromDate:self];
//日期的年月日
NSString *currentDay = [dateFormatterstringFromDate:[NSDate date]];
//當(dāng)前年月日
NSInteger timeInterval = -[self timeIntervalSinceNow];
if(timeInterval <60) {return@"1分鐘內(nèi)";? ? }
elseif(timeInterval <3600)
?{//1小時(shí)內(nèi)
return[NSStringstringWithFormat:@"%ld分鐘前", timeInterval /60];? ? }
elseif(timeInterval <21600) {//6小時(shí)內(nèi)
return[NSStringstringWithFormat:@"%ld小時(shí)前", timeInterval /3600];? ? }
elseif([theDayisEqualToString:currentDay]) {//當(dāng)天
[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.已經(jīng)知道當(dāng)前時(shí)間迷守,計(jì)算未來或者以前的時(shí)間
NSCalendar*calendar = [NSCalendarcurrentCalendar];? ?
?calendar.timeZone = [NSTimeZonelocalTimeZone];
NSDateComponents*comp = [calendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:date];//comp可以修改年月日等時(shí)間
[comp setDay:1];NSDate*firstDayOfMonthDate = [calendar dateFromComponents:comp];
4.固定app的時(shí)區(qū)犬绒,不會(huì)根據(jù)位置改變(下面是東八區(qū))
[NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+0800"]];