您的位置:首页 > 移动开发 > IOS开发

(iOS开发)计算时间差

2016-09-20 15:31 447 查看
方法1:(限定:IOS8.0之后使用)

//计算时间差
-(int)calculateTime
{
int timeResult=0;
NSDateFormatter *date=[[NSDateFormatter alloc] init];
[date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *messageTime=[[NSUserDefaults standardUserDefaults] objectForKey:@"lastTime"];
if (messageTime.length>0) {
NSDate *messageDate=[date dateFromString:messageTime];
NSCalendar *cal = [NSCalendar currentCalendar];
NSString *timeNow=[self getTimeNow];
NSDate *nowDate=[date dateFromString:timeNow];
unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *d = [cal components:unitFlags fromDate:messageDate toDate:nowDate options:0];
timeResult = (int)[d hour]*3600+(int)[d minute]*60+(int)[d second]+(int)[d day]*86400+(int)[d month]*2592000+(int)[d year]*31536000;
NSLog(@"timeResult: %d",timeResult);
if (timeResult<0) {
timeResult=0;
}
}
return timeResult;
}


-(NSString *)getTimeNow
{
NSDate *GMTDate = [NSDate date];
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
NSInteger interval = [timeZone secondsFromGMT];
NSDate *localeDate = [GMTDate dateByAddingTimeInterval:interval];
NSString *time=[NSString stringWithFormat:@"%@",localeDate];
NSString *timenow=[[NSString alloc]init];
timenow=[time substringToIndex:19];
return timenow;
}

方法2:

//后来时间
NSDate *currentDate = [NSDate date];//获取当前时间,日期

NSInteger nowtime=[currentDate timeIntervalSince1970];

//间隔时间

NSInteger intervalSinceNow =[self distanceTimeWithBeforeTime:begintime withNowDateTime:nowtime];

[submitLog saveLogDatadxID:_releationid timeValue:intervalSinceNow AssetsName:_AssetsName bookID:nil bookName:nil subjectID:_subjectID beginTime:beginDateString];

//初始时间
NSDate *currentDate = [NSDate date];//获取当前时间,日期

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

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

beginDateString = [dateFormatter stringFromDate:currentDate];

begintime =[currentDate timeIntervalSince1970];

//计算方法

- (NSInteger)distanceTimeWithBeforeTime:(NSInteger)beTime withNowDateTime:(NSInteger)nowTime

{

NSInteger distanceTime = nowTime - beTime;

return distanceTime;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: