美文网首页
两个日期的比较?

两个日期的比较?

作者: zcaaron | 来源:发表于2016-07-20 16:37 被阅读23次

    第一种: "compare:"

     // 时间字符串
        NSString *createdAtString = @"2015-11-20 11:10:05";
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
        NSDate *createdAtDate = [fmt dateFromString:createdAtString];
    
        // 手机当前时间
        NSDate *nowDate = [NSDate date];
    
        /**
         NSComparisonResult的取值
         NSOrderedAscending = -1L, // 升序, 越往右边越大
         NSOrderedSame,  // 相等
         NSOrderedDescending // 降序, 越往右边越小
         */
        // 获得比较结果(谁大谁小)
        NSComparisonResult result = [nowDate compare:createdAtDate];
    
        if (result == NSOrderedAscending) { // 升序, 越往右边越大
            NSLog(@"createdAtDate > nowDate");
        } else if (result == NSOrderedDescending) { // 降序, 越往右边越小
            NSLog(@"createdAtDate < nowDate");
        } else {
            NSLog(@"createdAtDate == nowDate");
        }
    

    第二种:"timeIntervalSince......"

    // 时间字符串
        NSString *createdAtString = @"2015-11-20 09:10:05";
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSDate *createdAtDate = [fmt dateFromString:createdAtString];
    
        // 手机当前时间
        //    NSDate *nowDate = [NSDate date];
    
        // 获得createdAtDate和nowDate的时间间隔(间隔多少秒)
        
        //    NSTimeInterval interval = [nowDate timeIntervalSinceDate:createdAtDate];
        NSTimeInterval interval = [createdAtDate timeIntervalSinceNow];
        
        NSLog(@"%f", interval);
    

    第三种:"components:............................."

    NSDateFormatter * fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    // 时间字符串
    NSString * createdAtString = @"2016-11-01 09:10:05";
    NSDate * createdAtDate = [fmt dateFromString: createdAtString];
    
    // 当前时间
    NSDate * nowDate = [NSDate date];
    
    // 获得NSCalendar
    NSCalendar * calendar = nil;
    if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
        calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    } else {
    calendar = [NSCalendar currentCalendar];
    }
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    NSDateComponents * cmps = [calendar components:unit fromDate:createdAtDate toDate:nowDate options:0];
    
    NSLog(@"%@",cmps);
    
    

    相关文章

      网友评论

          本文标题:两个日期的比较?

          本文链接:https://www.haomeiwen.com/subject/nppvjttx.html