NSDate

作者: 嘚嘚以嘚嘚 | 来源:发表于2017-12-05 15:03 被阅读0次

    获取当前时间

    -(NSString*)getCurrentTimestamp{

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

    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

    //现在时间,你可以输出来看下是什么格式

    NSDate *datenow = [NSDate date];

    //----------将nsdate按formatter格式转成nsstring

    NSString *currentTimeString = [formatter stringFromDate:datenow];

    NSLog(@"currentTimeString =  %@",currentTimeString);

    return currentTimeString;

    }

    两个时间进行比较

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

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

      NSDate *lastHourDate = [dateFormatter dateFromString:lastHour];

    NSDate *currentTimeDate = [dateFormatter dateFromString:[self getCurrentTimestamp]];

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

     NSDateComponents *cmps = [calendar components:type fromDate:lastHourDate toDate:currentTimeDate options:0];

    NSLog(@"两个时间相差%ld年%ld月%ld日%ld小时%ld分钟%ld秒", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);

    相关文章

      网友评论

          本文标题:NSDate

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