NSDate

作者: Miss_QL | 来源:发表于2018-02-27 10:53 被阅读11次

    NSDate类,是Objec-C 语言种时间的封装类,处理关于时间的一些功能。
    大致总结了一下:

    1、获取当前时间

    NSDate *nowDate = [NSDate date];
    

    2、零时区时间转化为当地时间

    NSDate * inputDate = [NSDate date];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString * str = [formatter stringFromDate:inputDate];
    NSLog(@"零时区时间 = %@, 当地时间 = %@", inputDate, str);
    

    3、根据时间戳的值转化为时间对象

    NSDate * pubDate = [NSDate dateWithTimeIntervalSince1970:[self.infoObj.pubDate floatValue]];
    

    4、计算时间间隔

    - (NSString *)CalDateIntervalFromData:(NSDate *)paramStartDate endDate:(NSDate*)paramEndDate{
        NSString * strResult = nil;
        NSCalendar * chineseClendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSUInteger unitFlags =  NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSDayCalendarUnit| NSMonthCalendarUnit | NSYearCalendarUnit;
    
    NSDateComponents * DateComponent = [chineseClendar components:unitFlags fromDate:paramStartDate toDate:paramEndDate options:0];
        NSInteger diffHour = [DateComponent hour];
        NSInteger diffMin = [DateComponent minute];
        NSInteger diffSec = [DateComponent second];
        NSInteger diffDay = [DateComponent day];
        NSInteger diffMon = [DateComponent month];
        NSInteger diffYear = [DateComponent year];
        
        if (diffYear>0) {
            strResult = [NSString stringWithFormat:@"%ld 年前",(long)diffYear];
        } else if(diffMon>0) {
            strResult = [NSString stringWithFormat:@"%ld 月前",(long)diffMon];
        } else if(diffDay>0) {
            strResult = [NSString stringWithFormat:@"%ld 天前",(long)diffDay];
        } else if(diffHour>0) {
            strResult = [NSString stringWithFormat:@"%ld 小时前",(long)diffHour];
        } else if(diffMin>0) {
            strResult = [NSString stringWithFormat:@"%ld 分钟前",(long)diffMin];
        } else if(diffSec>0) {
            strResult = [NSString stringWithFormat:@"%ld 秒前",(long)diffSec];
        } else {
            strResult = [NSString stringWithFormat:@"未知时间"];
        }
        [chineseClendar release];
        return strResult;
    }
    

    5、利用date加减月份

    // 给一个时间,给一个数,正数是以后n个月,负数是前n个月;
    -(NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(int)month {
        NSDateComponents *comps = [[NSDateComponents alloc] init];
        [comps setMonth:month];
        NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDate *mDate = [calender dateByAddingComponents:comps toDate:date options:0];
        return mDate;
    }
    

    相关文章

      网友评论

          本文标题:NSDate

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