(iOS开发)计算时间差

来源:互联网 发布:wps输入数据自动计算 编辑:程序博客网 时间:2024/04/30 17:59

方法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;}


0 0
原创粉丝点击