时间计算NSDate/ NSCalendar/ NSTimeZone实战

概述

iOS 里获取时间的对象叫NSDate,通常可以使用一个[NSDate date]来方便地初始化时间对象,但是这个初始化的时间对象生成的是GMT时间,Greenwich Mean Time(GMT)即格林威治时间(世界‘零’时区的时间),也就是说如果你本地的时区是(+8时区北京)的话,就应该比这个时间要多走8个小时。

1、 那如果想要获取当前手机上正在显示的时间怎么办呢?比较好的方法是通过NSTimeZone

+ (NSDate *)systemDate {
    NSDate *utcDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSTimeInterval timeInterval = [zone secondsFromGMTForDate: utcDate];
    NSDate *sysDate = [date dateByAddingTimeInterval: timeInterval];
    return sysDate;
}

2、 如果仅仅只是获取手机当前显示时间的字符串,通过NSDateFormatter就够了

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"yyyy-MM-dd hh:mm:ss";
NSString *sysDate = [formatter stringFromDate: [NSDate date]];

3、 按照第2条的结果,如果向服务器传时间参数,以 @{@"startTime":startTime, @"endTime":endTime}; 的格式传一个开始时间和一个结束时间的话,可以这样

// num 是开始时间距离现在的天数
NSDate *startDate = [[NSDate date] dateByAddingTimeInterval:- 24 * 3600 * num];
NSDate *endDate = [[NSDate date] dateByAddingTimeInterval: 1];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"yyyy-MM-dd hh:mm:ss";
NSString *startString = [formatter stringFromDate: startDate];
NSString *endString = [formatter stringFromDate: endDate];
NSArray *arr = @[startString, endString];

4、 但是如果是从服务器拿到一个UTC的时间字符串数组要全部转化成本地的时间的话,就得用到NSTimeZone了

+ (NSString *)getLocalDateFromUTCDate:(NSString *)utcStr formatter:(NSDateFormatter *)dateFormatter {
    //传入一个NSDateFormatter的原因是考虑到性能
    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    NSDate *utcDate = [dateFormatter dateFromString: utcStr];
    dateFormatter.timeZone = [NSTimeZone localTimeZone];
    NSString *dateString = [dateFormatter stringFromDate:utcDate];
    return dateString;
}

5、 相反的如果想要把本地的时间字符串转成UTC的时间字符串,(By the way)上传到服务器的时间通常是UTC时间,这样无论在手机系统内选择什么时区,上传的时间都是时区的时间

+ (NSString *)getUTCStrFormateLocalStr:(NSString *)localStr formatter:(NSDateFormatter *)dateFormatter {
    //这里localStr 注意是手机系统的本地时间
    dateFormatter.timeZone = [NSTimeZone systemTimeZone];
    NSDate *localDate = [dateFormatter dateFromString: localStr];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    NSString *dateString = [dateFormatter stringFromDate: localDate];
    return dateString;
}

6、 当需要距现在手机系统的时间 num 天之前的时间时

+ (NSDate *)passedDateWithCount:(NSInteger)num
{
    NSDate *date = [[NSDate systemDate] dateByAddingTimeInterval: - 24 * 3600 * num];
    return date;
}

7、 得到这个月的第一天和最后一天

+ (NSArray *)getMonthFirstAndLastDay:(NSDate *)date
{
    double interval = 0;
    NSDate *firstDate = nil;
    NSDate *lastDate = nil;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    BOOL OK = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:& firstDate interval:&interval forDate:date];
    
    if (OK) {
        lastDate = [firstDate dateByAddingTimeInterval: interval];
    }else {
        return @[@"",@""];
    }
    return @[firstDate, lastDate];
}

8、 距离现在过去了多久时间,常用于类似发朋友圈、发状态下面的时间提醒文字,这个方法的调用者对象传进来 的是一个UTC的NSDate对象

- (NSString *)coverDateBeforeNow:(NSDate *)pastDate
{
    if (self == nil) {
        return @"无记录";
    }
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSTimeInterval time = [zone secondsFromGMTForDate: pastDate];
    NSDate *sysDate = [pastDate dateByAddingTimeInterval: time];
    NSTimeInterval timeInterval = [sysDate timeIntervalSinceNow];
    timeInterval = - timeInterval;
    long temp = 0;
    NSString *result = nil;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }
    
    else if((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小时前",temp];
    }
    
    else if((temp = temp/24) <30){
        result = [NSString stringWithFormat:@"%ld天前",temp];
    }
    
    else if((temp = temp/30) <12){
        result = [NSString stringWithFormat:@"%ld月前",temp];
    }
    else{
        temp = temp/12;
        result = [NSString stringWithFormat:@"%ld年前",temp];
    }
    
    return  result;
}

9、根据给定的NSDate计算这个日期所在的月份的第一天的Date和最后一天的Date

+ (NSArray *)getMonthFirstAndLastDay:(NSDate *)date
{
    double interval = 0;
    NSDate *firstDate = nil;
    NSDate *lastDate = nil;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    BOOL OK = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:& firstDate interval:&interval forDate:date];
    
    if (OK) {
        lastDate = [firstDate dateByAddingTimeInterval:interval];
    }else {
        return @[@"",@""];
    }
    return @[firstDate, lastDate];
}

10、根据给定NSDate计算该日期是星期几

+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate
{
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"0", @"1", @"2", @"3", @"4", @"5", @"6", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}

你可能感兴趣的:(时间计算NSDate/ NSCalendar/ NSTimeZone实战)